最近在做相簿功能遇到一個問題,就是載入圖片的時候然後放大,感覺有點卡。圖片可能有點大,所以考慮用縮圖來實現。
也就是在查詢出來一個相簿圖片 ,一頁顯示幾十張,這幾十張用縮圖來顯示,看相信情況的時候想QQ相簿樣載入原圖放大拉取圖片相關資訊。所用到的技術就是圖片壓縮功能。現在功能已經實現看代碼。
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Drawing.Imaging;using System.IO;namespace WindowsFormsApplication1{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string pathPerc = @"D:\0046620140807150650cin.jpg"; string source = @"G:\0046620140807150650cin.jpg"; if (!File.Exists(pathPerc)) { File.Create(pathPerc).Close(); } else { File.Delete(pathPerc); File.Create(pathPerc).Close(); } getThumImage(source, 18, 3, pathPerc); } #region getThumImage /**/ /// <summary> /// 產生縮圖 /// </summary> /// <param name="sourceFile">原始圖片檔案</param> /// <param name="quality">品質壓縮比</param> /// <param name="multiple">收縮倍數</param> /// <param name="outputFile">輸出檔案名</param> /// <returns>成功返回true,失敗則返回false</returns> public static bool getThumImage(String sourceFile, long quality, int multiple, String outputFile) { try { long imageQuality = quality; Bitmap sourceImage = new Bitmap(sourceFile); ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg"); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, imageQuality); myEncoderParameters.Param[0] = myEncoderParameter; float xWidth = sourceImage.Width; float yWidth = sourceImage.Height; Bitmap newImage = new Bitmap((int)(xWidth / multiple), (int)(yWidth / multiple)); Graphics g = Graphics.FromImage(newImage); g.DrawImage(sourceImage, 0, 0, xWidth / multiple, yWidth / multiple); g.Dispose(); newImage.Save(outputFile, myImageCodecInfo, myEncoderParameters); return true; } catch { return false; } } #endregion getThumImage /**/ /// <summary> /// 擷取圖片編碼資訊 /// </summary> private static ImageCodecInfo GetEncoderInfo(String mimeType) { int j; ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } }}
看下壓縮後的圖片如下
11KB
壓縮前的圖片
這樣縮圖就成功了。