1. 程式人生 > 實用技巧 >分享一個專案中在用的圖片處理工具類(圖片縮放,旋轉,畫布格式,位元組,image,bitmap轉換等)

分享一個專案中在用的圖片處理工具類(圖片縮放,旋轉,畫布格式,位元組,image,bitmap轉換等)

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; } } }