c# – 来自Stream的位图:Bug?

我有一个非常奇怪的错误.我需要缩小图像,缩小质量并转换为JPEG.当我将文件保存在磁盘上时这一切都有效,但是当我将它保存到Stream时它不起作用.

System.Drawing.Bitmap bitmap = // valid Bitmap from Disk
System.IO.Stream stream = new MemoryStream();

// JPEG Encoding

System.Drawing.Imaging.ImageCodecInfo jpgEncoder = GetEncoder( System.Drawing.Imaging.ImageFormat.Jpeg );
System.Drawing.Imaging.Encoder encoder2 = System.Drawing.Imaging.Encoder.Quality;
System.Drawing.Imaging.EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters( 1 );
System.Drawing.Imaging.EncoderParameter parameter = new System.Drawing.Imaging.EncoderParameter( encoder2, qualityLevel );
parameters.Param[0] = parameter;

// Save downscaled on Disk and stream

bitmap.Save( stream, jpgEncoder, parameters );
bitmap.Save( @"C:\TestJPEG.jpg", jpgEncoder, parameters );

// some stream stuff

var bytes = ((MemoryStream)stream).ToArray();
System.IO.Stream inputStream = new MemoryStream( bytes );

// Load from disk and stream

Bitmap fromDisk = new Bitmap( @"C:\TestJPEG.jpg" ); // works
Bitmap fromStream = new Bitmap( inputStream ); // crash invalid parameter no inner message or description
Bitmap fromStream2 = (Bitmap)Bitmap.FromStream( inputStream ); // same error here
// also crashes if I load the "stream" named Stream

我也可以用Paint打开转换后的文件.
有什么建议?

编辑:
我在Windows 7 Professional上使用.Net Framework 4.0

EDIT2:
试过寻求的东西(答案被删除)

stream.Seek( 0, SeekOrigin.Begin );

它适用于“旧”流.但我需要从字节数组加载它.还是一样的崩溃

最佳答案 以下代码适用于我:

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);

您的代码有一些差异.哪一个导致你的问题取决于你找出来,我想:

>我用50L作为qualityLevel.当使用1,2,50或100时,我得到一个ArgumentException“参数无效”.因为我不知道你的qualityLevel变量的类型或值很可能是问题所在.
>我替换了你的GetEncoder方法.我不知道你的方法到底做了什么,所以可能是问题,但我对此表示怀疑.

点赞