Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net Drawing.Graphics.FromImage() returns blank black image

I'm trying to rescale uploaded jpeg in asp.net

So I go:

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

this saves a virgin black jpeg whatever file i give it. Though if i take input image stream immediately into done bitmap, it does recompress and save it fine, like:

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

Do i have to make some magic with g?

upd: i tried:

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

same story - pure black of correct dimensions

like image 522
joox Avatar asked Jun 02 '10 13:06

joox


1 Answers

Since you didn't fill the area with background of image you're reading from inputStream,you can only get a blank image that way.

Instead of using scaling the image,you can use Fill background into a resized area.

Check this out:

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

Hope this helps
Myra

like image 142
Myra Avatar answered Sep 19 '22 23:09

Myra