/// <summary>自動縮圖</summary>
/// <param name="img">檔案本體</param>
/// <param name="filePath">存放位置</param>
/// <param name="fileName">檔案名稱</param>
protected void reDrawingImg(byte[] imgBuffer, string filePath, string fileName) {
 System.Drawing.Image img = bufferToImage(imgBuffer);
 ImageFormat thisFormat = img.RawFormat;   //取得影像的格式
 int[] newWH = imgReSize(img.Width, img.Height);
 Bitmap imageOutput = new Bitmap(img, newWH[0], newWH[1]);
        //縮圖後存放指定位址
 imageOutput.Save(filePath + fileName, thisFormat);
 imageOutput.Dispose();   //釋放記憶體
 img.Dispose();               //釋放掉圖檔
}
/// <summary>將 byte[] 轉成 Image</summary>
/// <param name="Buffer">檔案本體 (byte[])</param>
private System.Drawing.Image bufferToImage(byte[] Buffer) {
 byte[] data = null;
 System.Drawing.Image oImage = null;
 MemoryStream oMemoryStream = null;
 Bitmap oBitmap = null;
 //建立副本
 data = (byte[])Buffer.Clone();
 try {
  oMemoryStream = new MemoryStream(data);
  //設定資料流位置
  oMemoryStream.Position = 0;
  oImage = System.Drawing.Image.FromStream(oMemoryStream);
  //建立副本
  oBitmap = new Bitmap(oImage);                
 } catch {
  throw;
 }
 finally {
  oMemoryStream.Close();
  oMemoryStream.Dispose();
  oMemoryStream = null;
 }
 return oBitmap;
}
/// <summary>等比縮圖 - 計算長寬</summary>
/// <param name="width">原始寬度</param>
/// <param name="height">原始高度</param>
protected int[] imgReSize(double width, double height) {
 int[] newWH = new int[2];
 double rate, rWidth, rHeight;
 if (width > height && width > 200) {
  //水平圖
  rWidth = 200;
  rate = rWidth / width;
  rHeight = height * rate;
  newWH[0] = (int)rWidth;
  newWH[1] = (int)rHeight;
 }
 else if (height > width && height > 150) {
  //垂直圖
  rHeight = 150;
  rate = rHeight / height;
  rWidth = width * rate;
  newWH[0] = (int)rWidth;
  newWH[1] = (int)rHeight;
 }
 else {
  newWH[0] = (int)width;
  newWH[1] = (int)height;
 }
 return newWH;
}
沒有留言:
張貼留言