C# 無損縮圖(方法1:使用Graphics)

  • 1595
  • 0
  • 2019-12-24

無損縮圖(方法1:使用Graphics)

public Stream getPicThumbnail(string filePath)
{

	//讀取圖檔
	System.Drawing.Image inputImage = System.Drawing.Image.FromStream(new MemoryStream(File.ReadAllBytes(filePath)));
	//縮圖,此處縮圖大小為800x600
	int high = inputImage.Height;
	int width = inputImage.Width;
	Bitmap thumbnailBitmap = new Bitmap(width, high);
	Graphics thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
	//這三個屬性設定圖片品質
	thumbnailGraph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
	thumbnailGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
	thumbnailGraph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
	//重繪圖片
	System.Drawing.Rectangle imageRectangle = new System.Drawing.Rectangle(0, 0, width, high);
	thumbnailGraph.DrawImage(inputImage, imageRectangle);
	//存檔
	MemoryStream oMemoryStream = new MemoryStream();
	thumbnailBitmap.Save(oMemoryStream, inputImage.RawFormat);
	oMemoryStream.Position = 0;
        //使用Graphics壓縮,這邊要先將Stream轉成Image後再另存才有壓縮效果,否則直接將Stream傳出時檔案大小無變化
	System.Drawing.Image resultImage = System.Drawing.Image.FromStream(oMemoryStream);
	oMemoryStream = new MemoryStream();
	resultImage.Save(oMemoryStream, inputImage.RawFormat);	

	//釋放資源
	thumbnailGraph.Dispose();
	thumbnailBitmap.Dispose();
	inputImage.Dispose();
	GC.Collect();

	return oMemoryStream;
}

回傳為Stream