3

I am using the below code to transform a bitmap to jpeg. The bitmap is being passed through at 300 dpi (horizontal/vertical resolution) but the CreateBitmapSourcefromHBitmap method always changes the subsequent jpeg to be saved at 96dpi.

Is there any way to set the source to retain the original 300dpi? The dpiX and dpiY values are read only.

Thanks in advance.

public static MemoryStream GetJpgMemoryStream(Bitmap bitMap, int jpgQuality)
{
    IntPtr hBitmap = bitMap.GetHbitmap();

    try
    {      

        BitmapSource source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

        var jpegBitmapEncoder = new JpegBitmapEncoder();

        jpegBitmapEncoder.QualityLevel = jpgQuality;
        jpegBitmapEncoder.Frames.Add(BitmapFrame.Create(source));

        var jpegStream = new MemoryStream();

        jpegBitmapEncoder.Save(jpegStream);

        jpegStream.Flush();


        return jpegStream;

    }
}

2 Answers2

0

The MSDN Forum has a discussion that's similar to your problem. The recommended answer is to not use the Interop, instead use a WriteableBitmap as the BitmapSource for the JPEG.

jimbojones
  • 682
  • 7
  • 19
0

You have to change the method used for generating the BitmapSource. You can use the method stated in fast converting Bitmap to BitmapSource wpf for generating BitmapSource. Here is the updated code.

    BitmapData data = bitMap.LockBits( 
                         new System.Drawing.Rectangle(0,0,bitMap.Width,bitMap.Height), 
                         System.Drawing.Imaging.ImageLockMode.ReadOnly, 
                         bitMap.PixelFormat);

    BitmapSource source = BitmapSource.Create(bitMap.Width, bitMap.Height, 
                                 bitMap.HorizontalResolution, bitMap.VerticalResolution, 
                                 System.Windows.Media.PixelFormats.Bgr24, null,
                                 data.Scan0, data.Stride*bitMap.Height, data.Stride);

    bitMap.UnlockBits(data);

    var jpegBitmapEncoder = new JpegBitmapEncoder();

    jpegBitmapEncoder.QualityLevel = jpgQuality;
    jpegBitmapEncoder.Frames.Add(BitmapFrame.Create(source));

    var jpegStream = new MemoryStream();

    jpegBitmapEncoder.Save(jpegStream);
Rijul Sudhir
  • 2,064
  • 1
  • 15
  • 19