C#创建缩略图(低质量和大尺寸问题)
public void CreateThumbnail(Image img1, Photo photo, string targetDirectoryThumbs) { int newWidth = 700; int newHeight = 700; double ratio = 0; if (img1.Width > img1.Height) { ratio = img1.Width / (double)img1.Height; newHeight = (int)(newHeight / ratio); } else { ratio = img1.Height / (double)img1.Width; newWidth = (int)(newWidth / ratio); } Image bmp1 = img1.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero); bmp1.Save(targetDirectoryThumbs + photo.PhotoID + ".jpg"); img1.Dispose(); bmp1.Dispose(); }
我已经放了700px
这样你就可以更好地了解问题。 这是原始图像和resize的图像。
有什么好建议吗?
谢谢,
岛
您应该会发现我对此问题的回答很有帮助。 它包含一个用于在C#中进行高质量图像缩放的示例。
我的另一个答案中的完整示例包括如何将图像保存为jpeg。
这是代码的相关部分……
/// /// Resize the image to the specified width and height. /// /// The image to resize. /// The width to resize to. /// The height to resize to. /// The resized image. public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, int width, int height) { //a holder for the result Bitmap result = new Bitmap(width, height); //use a graphics object to draw the resized image into the bitmap using (Graphics graphics = Graphics.FromImage(result)) { //set the resize quality modes to high quality graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //draw the image into the target bitmap graphics.DrawImage(image, 0, 0, result.Width, result.Height); } //return the resulting bitmap return result; }
如果图像包含缩略图,它会自动将其拉伸到所需的大小…这将使它看起来像垃圾(就像你的情况;))
直接离开MSDN ……
如果图像包含嵌入的缩略图图像,则此方法将检索嵌入的缩略图并将其缩放到请求的大小。 如果图像不包含嵌入的缩略图图像,则此方法通过缩放主图像来创建缩略图图像。
在你的情况下,我只是仔细检查了源图像的缩略图并获得了…
- 新的Windows缩略图:JPEG格式(偏移量:830大小:3234)
- 缩略图类型:JPEG
- Thumnail宽度:112
- 缩略图高度:84
尝试将原始图像绘制到另一个较小的图像,并保存结果。
Bitmap bmp1 = new Bitmap(newWidth, newHeight); Graphics g = Graphics.FromImage(bmp); g.DrawImage(img1, 0, 0, newWidth, newHeight); bmp1.Save(targetDirectoryThumbs + photo.PhotoID + ".jpg", ImageFormat.Jpeg);
您是否可以使用第三方应用程序? 如果是这样,您可能需要查看ImageMagick来管理缩略图创建。 有一个.NET包装器。
我写了一个免费的.dll,很容易做到这一点。 如果您想查看文档,就在这里…. Git Repository&Tutorial