近期在做相冊功能遇到一个问题,就是载入图片的时候然后放大,感觉有点卡。图片可能有点大,所以考虑用缩略图来实现。
也就是在查询出来一个相冊图片 ,一页显示几十张,这几十张用缩略图来显示,看相信情况的时候想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 /**/ ///看下压缩后的图片例如以下/// 生成缩略图 /// /// 原始图片文件 /// 质量压缩比 /// 收缩倍数 /// 输出文件名称 ///成功返回true,失败则返回false 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 /**/ ////// 获取图片编码信息 /// 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
压缩前的图片
这样缩略图就成功了。