在 asp.net 中调整图像大小而不会损失图像质量



我正在开发一个 ASP.NET 的Web应用程序,其中我允许我的用户上传jpeg,gif,bmp或png图像。如果上传的图像大小大于 1 mb 。然后我想将图像大小调整为15-16 Kb,任务为230 * 300而不会丢失图像质量.调整图像大小后应该在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;     
}

此代码用于我的项目中,请参考下面的代码。

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);
}

最新更新