.net Drawing.Graphics.FromImage()返回空白的黑色图像

joo*_*oox 5 asp.net graphics upload system.drawing rescale

我正在尝试在asp.net中重新调整上传的jpeg

所以我去:

Image original = Image.FromStream(myPostedFile.InputStream);
int w=original.Width, h=original.Height;

using(Graphics g = Graphics.FromImage(original))
{
 g.ScaleTransform(0.5f, 0.5f); ... // e.g.
 using (Bitmap done = new Bitmap(w, h, g))
 {
  done.Save( Server.MapPath(saveas), ImageFormat.Jpeg );
  //saves blank black, though with correct width and height
 }
}
Run Code Online (Sandbox Code Playgroud)

这节省了处女黑色jpeg我给它的任何文件.虽然如果我将输入图像流立即带入done位图,它会重新压缩并保存它,如:

Image original = Image.FromStream(myPostedFile.InputStream);
using (Bitmap done = new Bitmap(original))
{
 done.Save( Server.MapPath(saveas), ImageFormat.Jpeg );
}
Run Code Online (Sandbox Code Playgroud)

我必须用g制作一些魔法吗?

upd:我试过了:

Image original = Image.FromStream(fstream);
int w=original.Width, h=original.Height;
using(Bitmap b = new Bitmap(original)) //also tried new Bitmap(w,h)
 using (Graphics g = Graphics.FromImage(b))
 {
  g.DrawImage(original, 0, 0, w, h); //also tried g.DrawImage(b, 0, 0, w, h)
  using (Bitmap done = new Bitmap(w, h, g))
  {
   done.Save( Server.MapPath(saveas), ImageFormat.Jpeg );
  }
 }
Run Code Online (Sandbox Code Playgroud)

相同的故事 - 正确尺寸的纯黑色

Myr*_*yra 5

由于您没有使用 inputStream读取的图像背景填充区域,因此只能获得空白图像.

您可以使用填充背景到调整大小的区域,而不是使用缩放图像.

看一下这个:

Image img = Image.FromFile(Server.MapPath("a.png"));
int w = img.Width;
int h = img.Height;

//Create an empty bitmap with scaled size,here half
Bitmap bmp = new Bitmap(w / 2, h / 2);
//Create graphics object to draw
Graphics g = Graphics.FromImage(bmp);
//You can also use SmoothingMode,CompositingMode and CompositingQuality
//of Graphics object to preserve saving options for new image.        

//Create drawing area with a rectangle
Rectangle drect = new Rectangle(0, 0, bmp.Width, bmp.Height);
//Draw image into your rectangle area
g.DrawImage(img, drect);
//Save your new image
bmp.Save(Server.MapPath("a2.jpg"), ImageFormat.Jpeg);
Run Code Online (Sandbox Code Playgroud)

希望这有助于
迈拉