110,535
社区成员
发帖
与我相关
我的任务
分享
using (Bitmap bitmap = (Bitmap)Image.FromFile("file.jpg"))
{
using (Bitmap newBitmap = new Bitmap(bitmap))
{
newBitmap.SetResolution(300, 300);
newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
namespace Test.Common
{
/// <summary>
/// 提供图片转换工具
/// </summary>
public static class ImageTransUtility
{
/// <summary>
/// 该函数提供等比转换功能、图片仅进行压缩,不进行裁切.
/// </summary>
/// <param name="sourceFileName"></param>
/// <param name="targetFileName"></param>
/// <param name="maxWidth"></param>
/// <param name="maxHeight"></param>
public static void TranslateByEqualRatio(string sourceFileName, string targetFileName, int maxWidth, int maxHeight)
{
if (maxWidth <= 0 || maxHeight <= 0)
{
throw new ArgumentException("Width And Height Must More than zero");
}
Bitmap fullSizeImg = new Bitmap(sourceFileName);
int width = fullSizeImg.Width;
int height = fullSizeImg.Height;
if (width > maxWidth || height > maxHeight)
{
if (maxWidth - width < maxHeight - height)
{
decimal ratio = (decimal)height / width;
width = maxWidth;
height = (int)Decimal.Round(Convert.ToDecimal((decimal)maxWidth * (decimal)ratio));
}
else
{
decimal ratio = (decimal)width / height;
height = maxHeight;
width = (int)Decimal.Round(Convert.ToDecimal((decimal)maxHeight * (decimal)ratio));
}
}
var thumbnailBitmap = new Bitmap(width, height);
var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, width, height);
thumbnailGraph.DrawImage(fullSizeImg, imageRectangle);
thumbnailBitmap.Save(targetFileName, ImageFormat.Jpeg);
fullSizeImg.Dispose();
thumbnailGraph.Dispose();
thumbnailBitmap.Dispose();
}
}
}