tags:

views:

576

answers:

2

Hi, I have a really strange problem with Graphics.DrawImage method.

I have the PictureBox control in the Panel control with AllowScroll property = true. The program cuts the image on small parts basing on the area selected by the user.

I load the image 300x547 and select the area (the red rectangle):

alt text

program properly cuts the image:

alt text

then, I load another image 427x640:

alt text

and then, as the result I see that the image is not cut properly. Each img.jpg file has properly width & height but the drawn image is too small: alt text

here's the code snippet - it saves the bitmap area selected by the user:

  Image OriginalIMG= (Image)((PictureBox)panel1.Controls["picBox"]).Image.Clone()
  Bitmap bmp = new Bitmap(selectedAreaRECT.Width, selectedAreaRECT.Height);
  Graphics g = Graphics.FromImage(bmp);

  g.DrawImage(OriginalIMG, 0,0, selectedAreaRECT, GraphicsUnit.Pixel);
  g.Save();
  g.Dispose();

  bmp.Save(AppDomain.CurrentDomain.BaseDirectory + @"\Temp\" + "img1.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

As You see, the code is the same for the img1.jpg from image A and from Image B. I'm trying to resolve that stupid problem for too long, I don't know what's the reason of that problem. I tried different overloads of the DrawImage method, with no success

EDIT

Resolved! the dafault DPI value of the System.Drawing.Bitmap is = 96, if I open an image with DPI != 96 then the problem described above occurs. To get rid of it, I needed to use SetResolution method:

Bitmap result = new Bitmap(width, height);
result.SetResolution(OriginalIMG.HorizontalResolution, OriginalIMG.VerticalResolution);

that resolves the problem :) Thanks for everyone for help ! :)

+1  A: 

I'd try: (edited)

  g.DrawImage(
    OriginalIMG,
    new Rectangle( Point.Empty, bmp.Size ),
    selectedAreaRECT.X, selectedAreaRECT.Y,
    selectedAreaRECT.Width, selectedAreaRECT.Height, 
    GraphicsUnit.Pixel);

to see if it makes a difference.

Although it has nothing to do with your problem: you're forgetting to .Dispose() some things, and I'm not sure why you have to .Clone() the image.

danbystrom
there is no constructor like Yours
Tony
Constructor? You mean method? Opps, I'll update...
danbystrom
A: 

Thank you! This was giving me headaches!

Best regards, Stian Farstad

Stian Farstad