Saving DrawingVisual to an image file with a given DPI

后端 未结 3 561
感情败类
感情败类 2021-01-27 03:04

I have got a WPF application, and I would like to save a Canvas to a file with a correct DPI value. The Canvas size is the real physical size, eg. 20x10 cm, at 300 DPI, so it\'s

3条回答
  •  萌比男神i
    2021-01-27 03:51

    It seems the solution is the Bitmap SetResolution, after all. I tested it, and it looks like not affect the image quality after the JpegBitmapEncoder()! And the image resolution is untouched, keep the metadata, only the DPI will change!

    Helped this documentation: https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-set-jpeg-compression-level

    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
    encoder.QualityLevel = 100;
    BitmapFrame bFrame = BitmapFrame.Create(rtb, null, meta, icc);
    encoder.Frames.Add(bFrame);
    
    using (var stream = new MemoryStream())
    {
        encoder.Save(stream);
    
        using (var bmpOutput = new System.Drawing.Bitmap(stream))
        {
            System.Drawing.Imaging.ImageCodecInfo myEncoder = GetEncoder(ImageFormat.Jpeg); 
    
            var encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
            encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
    
            bmpOutput.SetResolution(300.0f, 300.0f);
            bmpOutput.Save(filePath, myEncoder, encoderParameters);
        }
    }
    

提交回复
热议问题