Re size image not working C# [duplicate]

我是研究僧i 提交于 2019-12-25 11:16:09

问题


Am re sizing an image with the following code

using (Image thumbnail = new Bitmap(100, 50))
{
  using (Bitmap source = new Bitmap(imageFile))
  {
    using (Graphics g = Graphics.FromImage(thumbnail))
    {
      g.CompositingQuality = CompositingQuality.HighQuality;
      g.InterpolationMode = InterpolationMode.HighQualityBicubic;
      g.SmoothingMode = SmoothingMode.HighQuality;
      g.SmoothingMode = SmoothingMode.AntiAlias;
      g.InterpolationMode = InterpolationMode.HighQualityBicubic;
      g.DrawImage(source, 0, 0, 100, 50);
    }
  }
  using (MemoryStream ms = new MemoryStream())
   {
     thumbnail.Save(ms, ImageFormat.Png);
     thumbnail.Save(dest, ImageFormat.Png);
   }
}

but it is not giving an image of any quality. pixelation is making the image wired.

i have also tried the code

image re size in stack

but am getting a black screen as the result instead of jpg am using png is the only difference.

any suggestion for improving the image quality. i have to re size the transparent image to a size 100by50.

Thanks in advance.


回答1:


Try this, Assuming you can use it

public static Image Resize(Image originalImage, int w, int h)
{
    //Original Image attributes
    int originalWidth = originalImage.Width;
    int originalHeight = originalImage.Height;

    // Figure out the ratio
    double ratioX = (double)w / (double)originalWidth;
    double ratioY = (double)h / (double)originalHeight;
    // use whichever multiplier is smaller
    double ratio = ratioX < ratioY ? ratioX : ratioY;

    // now we can get the new height and width
    int newHeight = Convert.ToInt32(originalHeight * ratio);
    int newWidth = Convert.ToInt32(originalWidth * ratio);

    Image thumbnail = new Bitmap(newWidth, newHeight);
    Graphics graphic = Graphics.FromImage(thumbnail);

    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphic.SmoothingMode = SmoothingMode.HighQuality;
    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphic.CompositingQuality = CompositingQuality.HighQuality;

    graphic.Clear(Color.Transparent);
    graphic.DrawImage(originalImage, 0, 0, newWidth, newHeight);

    return thumbnail;
}


来源:https://stackoverflow.com/questions/17140710/re-size-image-not-working-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!