Bitmap from Stream: Bug?

后端 未结 1 1563
迷失自我
迷失自我 2021-01-13 16:12

I have a pretty strange Error. I need to scale down images, scale down the quality and convert to JPEG. This all works when I save the File on disk, but it doesn\'t work whe

相关标签:
1条回答
  • 2021-01-13 17:01

    The following code works for me:

    var bitmap = new Bitmap(@"c:\Dokumente und Einstellungen\daniel.hilgarth\Desktop\Unbenannt.bmp");
    
    ImageCodecInfo jpgEncoder = ImageCodecInfo.GetImageEncoders().Single(x => x.FormatDescription == "JPEG");
    Encoder encoder2 = System.Drawing.Imaging.Encoder.Quality;
    EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters( 1 );
    EncoderParameter parameter = new EncoderParameter( encoder2, 50L );
    parameters.Param[0] = parameter;
    
    System.IO.Stream stream = new MemoryStream();
    bitmap.Save( stream, jpgEncoder, parameters );
    bitmap.Save(@"C:\Temp\TestJPEG.jpg", jpgEncoder, parameters);
    
    var bytes = ((MemoryStream)stream).ToArray();
    System.IO.Stream inputStream = new MemoryStream(bytes);
    Bitmap fromDisk = new Bitmap(@"C:\Temp\TestJPEG.jpg");
    Bitmap fromStream = new Bitmap(inputStream);
    

    There are a few differences to your code. Which one causes your problem is up to you to find out, I guess:

    • I used 50L as qualityLevel. When using 1, 2, 50 or 100, I was getting an ArgumentException "Parameter is not valid". As I don't know the type or value of your qualityLevel variable that can very well be the problem.
    • I replaced your GetEncoder method. I don't know what your method does exactly, so it could be the problem, but I doubt it.
    0 讨论(0)
提交回复
热议问题