using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Drawing; using System.Drawing.Drawing2D; using System.Threading; namespace ConfigLab.Comp.Img.ImgUtils { /// <summary> /// 功能簡介:圖片轉換類 /// 建立時間:2016-9-10 /// 建立人:pcw /// 博客:http://www.cnblogs.com/taohuadaozhu /// </summary> public class ImgConvert { /// <summary> /// 字節數組轉換爲bitmap /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static Bitmap BytesToBitmap(byte[] buffer) { Bitmap bitmapResult = null; if (buffer != null && buffer.Length > 0) { using (MemoryStream ms = new MemoryStream(buffer)) { try { bitmapResult = new Bitmap(ms); return bitmapResult; } catch (Exception error) { return bitmapResult; } finally { ms.Close(); ms.Dispose(); } } } return null; } /// <summary> /// 字節數組轉換爲Image對象 /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static Image BytesToImage(byte[] buffer) { if (buffer != null && buffer.Length > 0) { using (MemoryStream ms = new MemoryStream(buffer)) { Image image = null; try { image = Image.FromStream(ms); return image; } catch (Exception error) { return image; } finally { ms.Close(); ms.Dispose(); } } } return null; } /// <summary> /// 按照必定的比率進行放大或縮小 /// </summary> /// <param name="Percent">縮略圖的寬度百分比 如:須要百分之80,就填0.8</param> /// <param name="rotateFlipType"> ///順時針旋轉90度 RotateFlipType.Rotate90FlipNone ///逆時針旋轉90度 RotateFlipType.Rotate270FlipNone ///水平翻轉 RotateFlipType.Rotate180FlipY ///垂直翻轉 RotateFlipType.Rotate180FlipX ///保持原樣 RotateFlipType.RotateNoneFlipNone /// </param> /// <param name="IsTransparent">背景是否透明</param> /// <returns>Bitmap對象</returns> public static Bitmap GetImage_Graphics(Image ResourceImage, double Percent, RotateFlipType rotateFlipType, bool IsTransparent) { Bitmap ResultBmp = null; try { if (ResourceImage != null) { ResourceImage.RotateFlip(rotateFlipType); int _newWidth = (int)Math.Round(ResourceImage.Width * Percent); int _newHeight = (int)Math.Round(ResourceImage.Height * Percent); ResultBmp = new System.Drawing.Bitmap(_newWidth, _newHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);//建立圖片對象 Graphics g = null; try { g = Graphics.FromImage(ResultBmp);//建立畫板並加載空白圖像 if (g != null) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; //System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;//設置保真模式爲高度保真 g.DrawImage(ResourceImage, new Rectangle(0, 0, _newWidth, _newHeight), 0, 0, ResourceImage.Width, ResourceImage.Height, GraphicsUnit.Pixel);//開始畫圖 if (IsTransparent) { ResultBmp.MakeTransparent(System.Drawing.Color.Transparent); } } } catch (Exception errr) { ConfigLab.Utils.SaveErrorLog(string.Format("GetImage_Graphics(1),異常={0}", errr.Message)); Thread.Sleep(100); } finally { if (g != null) { g.Dispose(); } } } } catch (Exception ex) { ConfigLab.Utils.SaveErrorLog(string.Format("GetImage_Graphics(2),異常={0}", ex.Message)); Thread.Sleep(100); return null; } finally { if (ResourceImage != null) { ResourceImage.Dispose(); } } return ResultBmp; } /// <summary> /// 圖片等比縮放 /// </summary> /// <param name="sImgFilePath"></param> /// <param name="Percent"></param> /// <returns></returns> public static bool ChangeImgSize(string sImgFilePath, double Percent,string sNewImgFilePath) { Image img = null; Bitmap bp = null; bool bSuccess = false; try { if (File.Exists(sImgFilePath) == false) { Utils.SaveErrorLog(string.Format("找不到待壓縮的原文件{0}", sImgFilePath)); return false; } img = Image.FromFile(sImgFilePath); if (img != null) { bp = GetImage_Graphics(img, Percent, RotateFlipType.RotateNoneFlipNone, true); if (bp != null) { string sDirectory = FilePathUtils.getDirectory(sNewImgFilePath); if (sDirectory.EndsWith("\\") == false) { sDirectory = string.Format("{0}\\", sDirectory); } bp.Save(sNewImgFilePath); bSuccess=true; } } } catch(Exception ex) { Utils.SaveErrorLog(string.Format("ChangeImgSize處理{0}的圖片且保存到{1}的任務執行失敗",sImgFilePath,sNewImgFilePath), ex); } finally { if (img != null) { img.Dispose(); } if (bp != null) { bp.Dispose(); } } return bSuccess; } /// <summary> /// Resize圖片 /// </summary> /// <param name="bmp">原始Bitmap</param> /// <param name="newW">新的寬度</param> /// <param name="newH">新的高度</param> /// <returns>處理之後的Bitmap</returns> public static Bitmap ResizeBmp(Bitmap bmp, int newW, int newH) { try { Bitmap b = new Bitmap(newW, newH); Graphics g = Graphics.FromImage(b); g.SmoothingMode = SmoothingMode.HighSpeed; g.CompositingQuality = CompositingQuality.HighSpeed; g.InterpolationMode = InterpolationMode.Low; g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel); g.Dispose(); return b; } catch { return null; } } /// 將圖片Image轉換成Byte[] /// </summary> /// <param name="Image">image對象</param> /// <param name="imageFormat">後綴名</param> /// <returns></returns> public static byte[] ImageToBytes(Image Image, System.Drawing.Imaging.ImageFormat imageFormat) { if (Image == null) { return null; } byte[] data = null; using (MemoryStream ms = new MemoryStream()) { using (Bitmap Bitmap = new Bitmap(Image)) { Bitmap.Save(ms, imageFormat); ms.Position = 0; data = new byte[ms.Length]; ms.Read(data, 0, Convert.ToInt32(ms.Length)); ms.Flush(); } } return data; } /// <summary> /// 經過FileStream 來打開文件,這樣就能夠實現不鎖定Image文件,到時能夠讓多用戶同時訪問Image文件 /// </summary> /// <param name="path"></param> /// <returns></returns> public static Bitmap ReadImageFile(string path) { if (string.IsNullOrEmpty(path)) return null; if (File.Exists(path) == false) return null; int filelength = 0; Bitmap bit = null; Byte[] image = null; try { using (FileStream fs = File.OpenRead(path))//OpenRead { filelength = (int)fs.Length; //得到文件長度 image = new Byte[filelength]; //創建一個字節數組 fs.Read(image, 0, filelength); //按字節流讀取 System.Drawing.Image result = System.Drawing.Image.FromStream(fs); bit = new Bitmap(result); if (fs != null) { fs.Close(); fs.Dispose(); } } } catch (Exception err) { ConfigLab.Utils.SaveErrorLog(string.Format("讀取圖片【{0}】失敗,調試信息={1}", path, err.Message + err.StackTrace)); } finally { if (image != null) { image = null; } } return bit; } } }