1. 程式人生 > >C#/WPF 原圖轉成縮列圖

C#/WPF 原圖轉成縮列圖

本章講述:原圖轉成縮圖

double dWidth = System.Windows.SystemParameters.PrimaryScreenWidth;//顯示屏畫素 寬
double dHeight = System.Windows.SystemParameters.PrimaryScreenHeight;//顯示屏畫素  高

轉換實現:

public static void GenerateHighThumbnail(string oldImagePath, string newImagePath, int width, int height)
{
	System.Drawing.Image oldImage = System.Drawing.Image.FromFile(oldImagePath);
	int newWidth = AdjustSize(width, height, oldImage.Width, oldImage.Height).Width;
	int newHeight = AdjustSize(width, height, oldImage.Width, oldImage.Height).Height;
	//。。。。。。。。。。。
	System.Drawing.Image thumbnailImage = oldImage.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
	System.Drawing.Bitmap bm = new System.Drawing.Bitmap(thumbnailImage);
	bm.MakeTransparent(System.Drawing.Color.Black);
	//處理JPG質量的函式
	System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/png");
	if (ici != null)
	{
		System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);
		ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
		bm.Save(newImagePath, ici, ep);
		//釋放所有資源,不釋放,可能會出錯誤。
		ep.Dispose();
		ep = null;
	}
	ici = null;
	bm.Dispose();
	bm = null;
	thumbnailImage.Dispose();
	thumbnailImage = null;
	oldImage.Dispose();
	oldImage = null;
}
private static bool ThumbnailCallback()
{
	return false;
}
private static System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(String mimeType)
{
	int j;
	System.Drawing.Imaging.ImageCodecInfo[] encoders;
	encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
	for (j = 0; j < encoders.Length; ++j)
	{
		if (encoders[j].MimeType == mimeType)
			return encoders[j];
	}
	return null;
}
public struct PicSize
{
	public int Width;
	public int Height;
}
public static PicSize AdjustSize(int spcWidth, int spcHeight, int orgWidth, int orgHeight)
{
	PicSize size = new PicSize();
	// 原始寬高在指定寬高範圍內,不作任何處理 
	if (orgWidth <= spcWidth && orgHeight <= spcHeight)
	{
		size.Width = orgWidth;
		size.Height = orgHeight;
	}
	else
	{
		// 取得比例係數 
		float w = orgWidth / (float)spcWidth;
		float h = orgHeight / (float)spcHeight;
		// 寬度比大於高度比 
		if (w > h)
		{
			size.Width = spcWidth;
			size.Height = (int)(w >= 1 ? Math.Round(orgHeight / w) : Math.Round(orgHeight * w));
		}
		// 寬度比小於高度比 
		else if (w < h)
		{
			size.Height = spcHeight;
			size.Width = (int)(h >= 1 ? Math.Round(orgWidth / h) : Math.Round(orgWidth * h));
		}
		// 寬度比等於高度比 
		else
		{
			size.Width = spcWidth;
			size.Height = spcHeight;
		}
	}
	return size;
}