Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 图像大小调整:操作已成功完成_C#_Asp.net Mvc_Image Processing - Fatal编程技术网

C# 图像大小调整:操作已成功完成

C# 图像大小调整:操作已成功完成,c#,asp.net-mvc,image-processing,C#,Asp.net Mvc,Image Processing,大家早上好 我有以下问题:在MVC应用程序中,我创建了一个用于下载图像、缩放等的处理程序。它似乎工作得很好,但有时在事件查看器中我会出现错误,我不知道从哪里开始查找,甚至不知道如何寻找解决方案 错误:“操作已成功完成。”通过实例化“System.Windows.Media.Imaging.JpegBitmapEncoder”发生此错误 更新:代码 /// <summary> /// return byte of the resized image /// </summary&g

大家早上好

我有以下问题:在MVC应用程序中,我创建了一个用于下载图像、缩放等的处理程序。它似乎工作得很好,但有时在事件查看器中我会出现错误,我不知道从哪里开始查找,甚至不知道如何寻找解决方案

错误:“操作已成功完成。”通过实例化“System.Windows.Media.Imaging.JpegBitmapEncoder”发生此错误

更新:代码

/// <summary>
/// return byte of the resized image
/// </summary>
/// <param name="bytes">The bytes on original image.</param>
/// <param name="w">desidered width.</param>
/// <param name="h">desired height</param>
/// <param name="maxWidth">The maximum width.</param>
/// <param name="maxHeight">The maximum height.</param>
/// <param name="keepRatio">if set to <c>true</c> mantain ratio.</param>
/// <param name="crop">if set to <c>true</c> crop the resulting image.</param>
/// <param name="backgroudColor">Color of the backgroud.</param>
/// <param name="imageFormat">The image format.</param>
/// <param name="dpi">The dpi.</param>
/// <param name="quality">The quality.</param>
/// <returns></returns>

public static byte[] GetResizedImage(

        byte[] bytes
        , int? w
        , int? h
        , int? maxWidth
        , int? maxHeight
        , bool keepRatio
        , bool crop
        , string backgroudColor
        , string imageFormat
        , int dpi = 96
        , int quality = 90
)
{
    int width = w.HasValue && w > 0 ? w.Value : 0;
    int height = h.HasValue && h > 0 ? h.Value : 0;


    if (bytes.Length == 0)
    {
        return bytes;
    }
    Image img = null;
    using (MemoryStream stream = new MemoryStream(bytes))
    {
        img = Image.FromStream(stream);
    }

            /* se ho specificato maxwidth o maxwidth, devo verificare se devo fare il resize o meno */
    if (maxWidth.HasValue || maxHeight.HasValue)
    {
                /*  verifico se devo fare il resize */
        if (
                (maxWidth.HasValue && img.Width < maxWidth)
                        ||
                        (maxHeight.HasValue && img.Height < maxHeight)
                )
        {
            return bytes;
        }
        else
        {
            if (maxWidth.HasValue && (maxWidth < width || width <= 0))
            {
                width = maxWidth.Value;
            }
            if (maxHeight.HasValue && (maxHeight < height || height <= 0))
            {
                height = maxHeight.Value;
            }
        }
    }


    if (img.IsAnimated())
    {
                /* prendo il primo frame */
        img = img.GetFrame(0);
    }


    decimal resizeX = width;
    decimal resizeY = height;


    // Calcolo le dimensioni dell'immagine
            /* Se non ho specificato altezza o largnezza, ma il ratio
             * calcolo il parametro mancante*/
    if (height > 0 & width <= 0 && keepRatio)
    {
        width = height * img.Width / img.Height;
        resizeX = width;
    }
    else if (width > 0 & height <= 0 && keepRatio)
    {
        height = width * img.Height / img.Width;
        resizeY = height;
    }
    else
    {
                /* crop 
                   calcolo quale lato si deve adattare */
        if (crop)
        {
            if ((decimal)img.Width / (decimal)width > (decimal)img.Height / (decimal)height)
            {
                resizeY = height;
                resizeX = resizeY * img.Width / img.Height;
            }
            else
            {
                resizeX = width;
                resizeY = resizeX * img.Height / img.Width;
            }
        }
        else
        {
            if ((width * 100 / img.Width) < (height * 100 / img.Height))
            {
                // Se è più largo
                resizeX = width;
                resizeY = width * img.Height / img.Width;
            }
            else
            {
                // Se è più alto
                resizeY = height;
                resizeX = height * img.Width / img.Height;
            }
        }
    }


    int newW = width;
    int newH = height;

    if (keepRatio)
    {
        newW = (int)resizeX;
        newH = (int)resizeY;

    }


    // Disegno l'immagine
    using (Bitmap bmp = new Bitmap(width, height))
    {

        bmp.SetResolution(dpi, dpi);


        Color c = Color.White;
        if (imageFormat == CONTENT_TYPE_IMAGE_PNG)
        {
            c = Color.Transparent;
        }
        using (Graphics gr = Graphics.FromImage(bmp))
        {

            if (!String.IsNullOrEmpty(backgroudColor))
            {

                try
                {
                    if (backgroudColor.Substring(0, 1) != "#")
                    {
                        backgroudColor = String.Format("#{0}", backgroudColor);
                    }

                    c = System.Drawing.ColorTranslator.FromHtml(backgroudColor);

                }
                catch { }

            }
            gr.Clear(c);


            // Disegno l'immagine centrata
            gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //gr.InterpolationMode = InterpolationMode.Bicubic;

            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

            gr.DrawImage(img, (width - newW) / 2, (height - newH) / 2, newW, newH);

        }

        // Salvo l'immagine nello stream
        try
        {
            byte[] result = null;
            using (MemoryStream m = new MemoryStream())
            {
                var codec = GetImageCodeInfo(imageFormat);
                bmp.Save(m, GetImageCodeInfo(imageFormat), GetEncoderParameters(imageFormat));
                result = m.GetBuffer();
            }

            BitmapEncoder targetEncoder;
            if (imageFormat == CONTENT_TYPE_IMAGE_PNG)
            {
                targetEncoder = new PngBitmapEncoder()
                {

                };
            }
            else
            {
                targetEncoder = new JpegBitmapEncoder
                {
                    QualityLevel = quality
                };
            }

            var frame = ReadBitmapFrame(result);
            var resize = FastResize(frame, width, height);

            using (var memoryStream = new MemoryStream())
            {
                targetEncoder.Frames.Add(resize);
                targetEncoder.Save(memoryStream);
                result = memoryStream.ToArray();
            }


            targetEncoder = null;
            frame = null;
            resize = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();

            return result;
        }
        catch (System.Runtime.InteropServices.ExternalException)
        {
            //errore generico

            //TODO : loggare l'errore
            throw;
        }
        catch
        {
            throw;
        }
    }
}


public static BitmapFrame ReadBitmapFrame(byte[] bytes)
{
    BitmapFrame result;

    using (MemoryStream photoStream = new MemoryStream(bytes))
    {
        var photoDecoder = BitmapDecoder.Create(
                photoStream,
                BitmapCreateOptions.PreservePixelFormat,
                BitmapCacheOption.None);

        result = photoDecoder.Frames[0];
    }
    return result;
}


public static BitmapFrame FastResize(BitmapFrame photo, int width, int height)
{
    var target = new TransformedBitmap(
            photo,
            new System.Windows.Media.ScaleTransform(
                    width / photo.Width,
                    height / photo.Height,
                    0, 0));
    return BitmapFrame.Create(target);
}
//
///返回已调整大小的图像的字节
/// 
///原始图像上的字节数。
///设计宽度。
///理想高度
///最大宽度。
///最大高度。
///如果设置为真mantain比率。
///如果设置为true,则裁剪生成的图像。
///背景的颜色。
///图像格式。
///新闻部。
///质量。
/// 
公共静态字节[]GetResizedImage(
字节[]字节
,int?w
,int?h
,int?最大宽度
,int?最大高度
,布尔·基普拉蒂奥
,粗粮作物
,字符串背景颜色
,字符串图像格式
,int dpi=96
,整数质量=90
)
{
int width=w.HasValue&&w>0?w.值:0;
int height=h.HasValue&&h>0?h.值:0;
if(bytes.Length==0)
{
返回字节;
}
图像img=null;
使用(内存流=新内存流(字节))
{
img=Image.FromStream(流);
}
/*指定的最大宽度和最大宽度,数据验证数据的大小和菜单的大小*/
if(maxWidth.HasValue | | maxHeight.HasValue)
{
/*验证设备的价格*/
如果(
(maxWidth.HasValue&&img.Widthif(maxWidth.HasValue&&(maxWidth/// <summary>
/// return byte of the resized image
/// </summary>
/// <param name="bytes">The bytes on original image.</param>
/// <param name="w">desidered width.</param>
/// <param name="h">desired height</param>
/// <param name="maxWidth">The maximum width.</param>
/// <param name="maxHeight">The maximum height.</param>
/// <param name="keepRatio">if set to <c>true</c> mantain ratio.</param>
/// <param name="crop">if set to <c>true</c> crop the resulting image.</param>
/// <param name="backgroudColor">Color of the backgroud.</param>
/// <param name="imageFormat">The image format.</param>
/// <param name="dpi">The dpi.</param>
/// <param name="quality">The quality.</param>
/// <returns></returns>

public static byte[] GetResizedImage(

        byte[] bytes
        , int? w
        , int? h
        , int? maxWidth
        , int? maxHeight
        , bool keepRatio
        , bool crop
        , string backgroudColor
        , string imageFormat
        , int dpi = 96
        , int quality = 90
)
{
    int width = w.HasValue && w > 0 ? w.Value : 0;
    int height = h.HasValue && h > 0 ? h.Value : 0;


    if (bytes.Length == 0)
    {
        return bytes;
    }
    Image img = null;
    using (MemoryStream stream = new MemoryStream(bytes))
    {
        img = Image.FromStream(stream);
    }

            /* se ho specificato maxwidth o maxwidth, devo verificare se devo fare il resize o meno */
    if (maxWidth.HasValue || maxHeight.HasValue)
    {
                /*  verifico se devo fare il resize */
        if (
                (maxWidth.HasValue && img.Width < maxWidth)
                        ||
                        (maxHeight.HasValue && img.Height < maxHeight)
                )
        {
            return bytes;
        }
        else
        {
            if (maxWidth.HasValue && (maxWidth < width || width <= 0))
            {
                width = maxWidth.Value;
            }
            if (maxHeight.HasValue && (maxHeight < height || height <= 0))
            {
                height = maxHeight.Value;
            }
        }
    }


    if (img.IsAnimated())
    {
                /* prendo il primo frame */
        img = img.GetFrame(0);
    }


    decimal resizeX = width;
    decimal resizeY = height;


    // Calcolo le dimensioni dell'immagine
            /* Se non ho specificato altezza o largnezza, ma il ratio
             * calcolo il parametro mancante*/
    if (height > 0 & width <= 0 && keepRatio)
    {
        width = height * img.Width / img.Height;
        resizeX = width;
    }
    else if (width > 0 & height <= 0 && keepRatio)
    {
        height = width * img.Height / img.Width;
        resizeY = height;
    }
    else
    {
                /* crop 
                   calcolo quale lato si deve adattare */
        if (crop)
        {
            if ((decimal)img.Width / (decimal)width > (decimal)img.Height / (decimal)height)
            {
                resizeY = height;
                resizeX = resizeY * img.Width / img.Height;
            }
            else
            {
                resizeX = width;
                resizeY = resizeX * img.Height / img.Width;
            }
        }
        else
        {
            if ((width * 100 / img.Width) < (height * 100 / img.Height))
            {
                // Se è più largo
                resizeX = width;
                resizeY = width * img.Height / img.Width;
            }
            else
            {
                // Se è più alto
                resizeY = height;
                resizeX = height * img.Width / img.Height;
            }
        }
    }


    int newW = width;
    int newH = height;

    if (keepRatio)
    {
        newW = (int)resizeX;
        newH = (int)resizeY;

    }


    // Disegno l'immagine
    using (Bitmap bmp = new Bitmap(width, height))
    {

        bmp.SetResolution(dpi, dpi);


        Color c = Color.White;
        if (imageFormat == CONTENT_TYPE_IMAGE_PNG)
        {
            c = Color.Transparent;
        }
        using (Graphics gr = Graphics.FromImage(bmp))
        {

            if (!String.IsNullOrEmpty(backgroudColor))
            {

                try
                {
                    if (backgroudColor.Substring(0, 1) != "#")
                    {
                        backgroudColor = String.Format("#{0}", backgroudColor);
                    }

                    c = System.Drawing.ColorTranslator.FromHtml(backgroudColor);

                }
                catch { }

            }
            gr.Clear(c);


            // Disegno l'immagine centrata
            gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //gr.InterpolationMode = InterpolationMode.Bicubic;

            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

            gr.DrawImage(img, (width - newW) / 2, (height - newH) / 2, newW, newH);

        }

        // Salvo l'immagine nello stream
        try
        {
            byte[] result = null;
            using (MemoryStream m = new MemoryStream())
            {
                var codec = GetImageCodeInfo(imageFormat);
                bmp.Save(m, GetImageCodeInfo(imageFormat), GetEncoderParameters(imageFormat));
                result = m.GetBuffer();
            }

            BitmapEncoder targetEncoder;
            if (imageFormat == CONTENT_TYPE_IMAGE_PNG)
            {
                targetEncoder = new PngBitmapEncoder()
                {

                };
            }
            else
            {
                targetEncoder = new JpegBitmapEncoder
                {
                    QualityLevel = quality
                };
            }

            var frame = ReadBitmapFrame(result);
            var resize = FastResize(frame, width, height);

            using (var memoryStream = new MemoryStream())
            {
                targetEncoder.Frames.Add(resize);
                targetEncoder.Save(memoryStream);
                result = memoryStream.ToArray();
            }


            targetEncoder = null;
            frame = null;
            resize = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();

            return result;
        }
        catch (System.Runtime.InteropServices.ExternalException)
        {
            //errore generico

            //TODO : loggare l'errore
            throw;
        }
        catch
        {
            throw;
        }
    }
}


public static BitmapFrame ReadBitmapFrame(byte[] bytes)
{
    BitmapFrame result;

    using (MemoryStream photoStream = new MemoryStream(bytes))
    {
        var photoDecoder = BitmapDecoder.Create(
                photoStream,
                BitmapCreateOptions.PreservePixelFormat,
                BitmapCacheOption.None);

        result = photoDecoder.Frames[0];
    }
    return result;
}


public static BitmapFrame FastResize(BitmapFrame photo, int width, int height)
{
    var target = new TransformedBitmap(
            photo,
            new System.Windows.Media.ScaleTransform(
                    width / photo.Width,
                    height / photo.Height,
                    0, 0));
    return BitmapFrame.Create(target);
}