最近在做相册功能遇到一个问题,就是加载图片的时候然后放大,感觉有点卡。图片可能有点大,所以考虑用缩略图来实现。
也就是在查询出来一个相册图片 ,一页显示几十张,这几十张用缩略图来显示,看相信情况的时候想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
压缩前的图片
这样缩略图就成功了。
原文地址:http://blog.csdn.net/szstephenzhou/article/details/38900345