是否可以在WebImage类中设置jpeg图像的压缩级别?

时间:2015-10-23 15:09:42

标签: c# asp.net-mvc image-uploading

是否可以在WebImage类中设置jpeg图像的压缩级别?或者我是否必须使用Image类?

1 个答案:

答案 0 :(得分:0)

您必须先使用Image来压缩它。压缩后,您可以在WebImage上使用它。

下面是一个示例,我将base64转换为图像,但尝试理解压缩逻辑(80L是压缩级别):

public MemoryStream Base64ToJpeg(string imgFoto)
{
    Image imagemASerAjustada = null;
    Bitmap bmpTemporario = null;
    MemoryStream imagemCompactadaStream = new MemoryStream();
    EncoderParameters myEncoderParameters = new EncoderParameters(1);
    try
    {
        // removemos o cabeçalho a respeito do tipo da imagem
        string base64 = imgFoto.Substring(imgFoto.IndexOf(',') + 1);
        base64 = base64.Trim('\0');
        // convertemos em um array de bytes
        byte[] img = Convert.FromBase64String(base64);

        // transformamos a base64 em imagem
        imagemASerAjustada = Image.FromStream(new MemoryStream(img));
        // convertemos a imagem em Bitmap
        bmpTemporario = new Bitmap(imagemASerAjustada, new Size(140, 140));
        ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
        // Create an EncoderParameters object.
        // An EncoderParameters object has an array of EncoderParameter
        // objects. In this case, there is only one
        // EncoderParameter object in the array.
        Encoder myEncoder = Encoder.Quality;
        using (EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 80L))
        { 
            myEncoderParameters.Param[0] = myEncoderParameter;
            bmpTemporario.Save(imagemCompactadaStream, jpgEncoder, myEncoderParameters);
        }
        return imagemCompactadaStream;
    }
    catch
    {
        throw;
    }
    finally
    {
        if (imagemCompactadaStream.Length > 0)
        { 
            imagemASerAjustada.Dispose();
            bmpTemporario.Dispose();
            myEncoderParameters.Dispose();
        }
    }
}

私有ImageCodecInfo GetEncoder(ImageFormat格式)     {         ImageCodecInfo [] codecs = ImageCodecInfo.GetImageDecoders();

    foreach (ImageCodecInfo codec in codecs)
    {
        if (codec.FormatID == format.Guid)
        {
            return codec;
        }
    }
    return null;
}

您可以将流保存在WebImage(流)