zoukankan      html  css  js  c++  java
  • WebForm使用FileUpload控件上传压缩二进制图片

    fuImage 是FileUpload页面控件
    ImageHelper.CompressionImage(fuImage.FileBytes, quality);

    /// <summary> /// Convert Byte[] to Image /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static Image BytesToImage(byte[] buffer) { MemoryStream ms = new MemoryStream(buffer); Image image = System.Drawing.Image.FromStream(ms); return image; } /// <summary> /// Convert Byte[] to a picture and Store it in file /// </summary> /// <param name="fileName"></param> /// <param name="buffer"></param> /// <returns></returns> public static string CreateImageFromBytes(string fileName, byte[] buffer) { string file = fileName; Image image = BytesToImage(buffer); ImageFormat format = image.RawFormat; if (format.Equals(ImageFormat.Jpeg)) { file += ".jpeg"; } else if (format.Equals(ImageFormat.Png)) { file += ".png"; } else if (format.Equals(ImageFormat.Bmp)) { file += ".bmp"; } else if (format.Equals(ImageFormat.Gif)) { file += ".gif"; } else if (format.Equals(ImageFormat.Icon)) { file += ".icon"; } System.IO.FileInfo info = new System.IO.FileInfo(file); System.IO.Directory.CreateDirectory(info.Directory.FullName); File.WriteAllBytes(file, buffer); return file; } /// <summary> /// 壓縮圖片 /// </summary> /// <param name="fileStream">圖片流</param> /// <param name="quality">壓縮質量0-100之間 數值越大質量越高</param> /// <returns></returns> private byte[] CompressionImage(Stream fileStream, long quality) { using (System.Drawing.Image img = System.Drawing.Image.FromStream(fileStream)) { using (Bitmap bitmap = new Bitmap(img)) { ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality); myEncoderParameters.Param[0] = myEncoderParameter; using (MemoryStream ms = new MemoryStream()) { bitmap.Save(ms, CodecInfo, myEncoderParameters); myEncoderParameters.Dispose(); myEncoderParameter.Dispose(); return ms.ToArray(); } } } } private static ImageCodecInfo GetEncoder(ImageFormat format) { ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); foreach (ImageCodecInfo codec in codecs) { if (codec.FormatID == format.Guid) { return codec; } } return null; }
  • 相关阅读:
    【pytorch】torch.manual_seed()用法详解
    【python】具体能做些什么?(有哪些应用领域)
    【python】函数参数前加*星号的含义
    【python】Keyword-Only Arguments(强制关键字参数)
    【python】字符串find()方法
    碧蓝航线内部表情包(有爱自取)
    【python】60行代码实现给头像戴上圣诞帽(opencv)
    【python】30行代码实现视频中的动漫人脸检测(opencv)
    Linux supervisord配置使用 ubuntu
    BananaPi python-Mysql 操作库
  • 原文地址:https://www.cnblogs.com/Gxiaopan/p/6656864.html
Copyright © 2011-2022 走看看