为什么当我调整 JpegBitmapEncoder QualityLevel 时文件大小总是不改变?

Why doesn't file size always change when I adjust JpegBitmapEncoder QualityLevel?

我正在尝试保存 WritableBitmap,并确保生成的文件小于特定大小。我的代码如下

//Fetch Image from file
BitmapImage bitmap = new BitmapImage(new Uri("YourImage.jpg", UriKind.Relative));
WriteableBitmap writableBitmapImage = new WriteableBitmap(bitmap);

//initialize variables and values
MemoryStream stream;
JpegBitmapEncoder encoder;
byte[] result;
int quality = 100;

//loop through save process, checking file size and changing quality
while (selected.maxFileSize < result.Length && quality > 1)
{
    encoder = new JpegBitmapEncoder();
    stream = new MemoryStream();
    encoder.QualityLevel = quality;
    encoder.Frames.Add(BitmapFrame.Create(
        ReplaceTransparency(writableBitmapImage, Colors.White))
    );
    encoder.Save(stream);
    result = stream.GetBuffer();
    if (quality > 5) quality += -5;
    else quality--;
}

当我 运行 这段代码时,我没有看到从 QualityLevel = 100; 的起点到 QualityLevel = 10; 的任何文件大小变化。

QualityLevel = 5;,我发现文件大小发生了很大变化。

有没有办法更精细地控制文件大小?

阅读 MemoryStream.GetBuffer() 的文档:

Note that the buffer contains allocated bytes which might be unused. For example, if the string "test" is written into the MemoryStream object, the length of the buffer returned from GetBuffer is 256, not 4, with 252 bytes unused. To obtain only the data in the buffer, use the ToArray method; however, ToArray creates a copy of the data in memory.

那就用.ToArray()代替。