我正在开发一个ASP.NET Web应用程序,我允许我的用户上传jpeg,gif,bmp或png图像。如果上传的图像大小超过1 mb。然后我想将图像大小调整为15-16 Kb,并且不会丢失图像质量。在调整大小后,图像应该在230 * 300的距离内查看,请帮助我。
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValid)
{
Bitmap image = ResizeImage(fileImage.PostedFile.InputStream, 400, 800);
image.Save(Server.MapPath("~/Photos/") + Guid.NewGuid().ToString() + ".jpg", ImageFormat.Jpeg);
image.Dispose();
}
}
private Bitmap ResizeImage(Stream streamImage, int maxWidth, int maxHeight)
{
Bitmap originalImage = new Bitmap(streamImage);
int newWidth = originalImage.Width;
int newHeight = originalImage.Height;
double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
if (aspectRatio <= 1 && originalImage.Width > maxWidth)
{
newWidth = maxWidth;
newHeight = (int)Math.Round(newWidth / aspectRatio);
}
else if (aspectRatio > 1 && originalImage.Height > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)Math.Round(newHeight * aspectRatio);
}
Bitmap newImage = new Bitmap(originalImage, newWidth, newHeight);
Graphics g = Graphics.FromImage(newImage);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
originalImage.Dispose();
return newImage;
}
答案 0 :(得分:0)
我的项目中使用了此代码,请参考以下代码。
private Image RezizeI(Image img, int maxW, int maxH)
{
if(img.Height < maxH && img.Width < maxW) return img;
using (img)
{
Double xRatio = (double)img.Width / maxW;
Double yRatio = (double)img.Height / maxH;
Double ratio = Math.Max(xRatio, yRatio);
int nnx = (int)Math.Floor(img.Width / ratio);
int nny = (int)Math.Floor(img.Height / ratio);
Bitmap cpy = new Bitmap(nnx, nny, PixelFormat.Format32bppArgb);
using (Graphics gr = Graphics.FromImage(cpy))
{
gr.Clear(Color.Transparent);
// This is said to give best quality when resizing images
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.DrawImage(img,
new Rectangle(0, 0, nnx, nny),
new Rectangle(0, 0, img.Width, img.Height),
GraphicsUnit.Pixel);
}
return cpy;
}
}
private MemoryStream BytearrayToStream(byte[] arr)
{
return new MemoryStream(arr, 0, arr.Length);
}
private void HandleImageUpload(byte[] binaryImage)
{
Image img = RezizeI(Image.FromStream(BytearrayToStream(binaryImage)), 103, 32);
img.Save("Test.png", System.Drawing.Imaging.ImageFormat.Gif);
}