0

我编写了缩放 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;
}

此代码工作正常,但有时结果图像损坏如下 在此处输入图像描述

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

非常感谢!

电通

4

0 回答 0