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; }
posted @ 2017-04-01 17:24  一生有你.Net  阅读(529)  评论(0编辑  收藏  举报