How to save an Emgu `Image<Bgr, Byte> frame` in a memory stream as JPEG?

Daniel Gartmann picture Daniel Gartmann · Apr 16, 2012 · Viewed 16.4k times · Source

How can I save an Emgu Image<Bgr, Byte> frame in a memory stream as JPEG?

Answer

Chris picture Chris · Apr 17, 2012

You have two options the first is the native EMGU images.save("filename"); method however the quality is not great and lossy. The best method is to use the following c# method.

This is the function is saveJpeg(SaveFile.FileName, img.ToBitmap(), 100);. Based on the method saveJpeg(string path, Bitmap img, long quality).

using System.Drawing.Imaging;

private void saveJpeg(string path, Bitmap img, long quality)
{
    // Encoder parameter for image quality

    EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

    // Jpeg image codec
    ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");

    if (jpegCodec == null)
    return;

    EncoderParameters encoderParams = new EncoderParameters(1);
    encoderParams.Param[0] = qualityParam;

    img.Save(path, jpegCodec, encoderParams);
}

private ImageCodecInfo getEncoderInfo(string mimeType)
{
    // Get image codecs for all image formats
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

    // Find the correct image codec
    for (int i = 0; i < codecs.Length; i++)
    if (codecs[i].MimeType == mimeType)
    return codecs[i];
    return null;
}

hope this helps,

Cheers,

Chris