Image is damaged when using JpegBitmapEncoder?

2019-08-28 20:53发布

I wrote the function that Scale the jpeg and store into file as below

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

This code work ok, but sometime it the result image is damaged as below enter image description here

Plese help me, how to fix this bug?

Many thanks!

T&T

0条回答
登录 后发表回答