Preserving Bitmap values when creating a new Bitmap from System.Drawing.Image
- by Otaku
I'm trying to create a resized image from a bitmap, set a new height/width and a new resolution and save it to PNG. I can do this either from directly A) Image.FromFile(filename) or B) New Bitmap(imageSource) to create the the A Bitmap to be passed to B. Both work okay schmokay, but A does not allow me to set a new width/height on creation (but it does allow me to preserve values with useIcm=True) and B does not allow me to preseve values.
Okay, now on to some code and examples:
Dim sourceBitmap As New
Bitmap(imagePath & myImage1Name)
<-not good at all (#1 overload). Doesn't preserve
things like HorizontalResolution
or PixelFormat on .Save
Dim sourceBitmap2 As Bitmap = Image.FromFile(imagePath & myImage1Name,
True) <-not good (#5 overload). it does
preserve things like
HorizontalResolution or
PixelFormat on .Save, but it
doesn't allow me to initialize image at a new size.
Dim targetBitmap As New
Bitmap(sourceBitmap2, newWidth,
newHeight) <-not good. Even though
sourceBitmap2 (see #2 above) was
initialized with useIcm=True, it
doesn't matter once I've passed it
in as the source in targetBitmap.
Basically, I'm looking for a way to contruct a New Bitmap with both something like useIcm=True and set the width/height at the same time (Width/Height are read-only properties once it's created).
I've gone down the Graphics.DrawImage route as well and it's the same - Graphics.FromImage(sourceBitmap) does not preserve values.
Why do I need these values to be preserved? Because I need to convert these pictures to PNG (for file size) with a new resolution and keep the same physical dimensions (w/h in inches) for printing. I know the new pixel width/height needed based on the resolution values I'll pass in with .SetResolution(xDpi,yDpi) to preserve physical dimensions, so that's not the problem. The issue is things like the PixelFormatSize need to remain unchanged (yes, I've tried EncoderParameters - they don't work. I can give you the gory details if you like, but suffice it to say for now, they just don't work).
Whew, got that off my chest! Okay, anyone who really knows how all this works can help?