使用JpegBitmapEncoder时图像是否损坏?

时间:2014-04-04 10:11:28

标签: c# c++ jpegbitmapencoder

我编写了将jpeg缩放并存储到文件中的函数,如下所示

bool ResizeJpeg(unsigned char* _jpegDataBuff, int _buffLength, int _newSize_X, int _newSize_Y)
{
    try
    {
        //Decode to bitmap
        UnmanagedMemoryStream^ mStream = gcnew UnmanagedMemoryStream(_jpegDataBuff, _buffLength);
        JpegBitmapDecoder^ decoder = gcnew JpegBitmapDecoder(mStream, BitmapCreateOptions::PreservePixelFormat, BitmapCacheOption::OnLoad);
        BitmapSource^ bitmapSource = decoder->Frames[0];

        //Scale bitmap into new size
        BitmapSource^ bitmapSourceScaled = ResizeBitmap(bitmapSource, _newSize_X, _newSize_Y);

        //Encode to Jpeg
        FileStream^ fileStream = gcnew FileStream("1.jpg", FileMode::Create);
        JpegBitmapEncoder^ encoder = gcnew JpegBitmapEncoder();
        encoder->QualityLevel = _quality;
        encoder->Frames->Add(BitmapFrame::Create(bitmapSourceScaled));
        encoder->Save(fileStream);
        fileStream->Close();

        return true;
    }
    catch (System::Exception^)
    {
        return false;
    }
}

BitmapSource ResizeBitmap(BitmapSource source, double nWidth, double nHeight)
{
    TransformedBitmap tbBitmap = new TransformedBitmap(source,
                                              new ScaleTransform(nWidth / source.PixelWidth,
                                                  nHeight / source.PixelHeight, 0, 0));
    return tbBitmap;
}

此代码工作正常,但有时它会导致结果图像损坏,如下所示 enter image description here

请帮帮我,如何修复这个错误?

非常感谢!

T& T公司

0 个答案:

没有答案