C # GDI + функция изменения размера изображения

2

Итак, моя логика ошибочна, и мне нужен лучший и правильный способ изменить размер изображения в моем приложении С#

Мне нужна функция, подобная этой настройке

public void ResizeImageForWeb(string OriginalFile, string NewFile, int MaxWidth, int MaxHeight, int Quality)
{
// Resize Code

}

В принципе, я веб-дизайнер потерял попытку программирования настольного приложения.

  • 0
    Что такое int Quality ?
  • 0
    Качество изображения, от 1 до 100 от того, как сжато JPG
Показать ещё 2 комментария
Теги:
image
resize
gdi+

4 ответа

0
Лучший ответ

Быстрый поиск из Google обнаруживает это маленькое snippet.

  • 0
    Это фрагмент, который я использую в этом случае. +1.
  • 0
    Как я могу уменьшить размер файла, используя эту функцию?
Показать ещё 3 комментария
8

Это код, который я использовал для изменения размера изображений, загружаемых пользователями, для создания миниатюры или просто для ограничения размера. Он не учитывает качество изображения, но это начало.

// uses System.Drawing namespace
public class ImageResizer
{
    public bool ResizeImage(string fullFileName, int maxHeight, int maxWidth)
    {
        return this.ResizeImage(fullFileName, maxHeight, maxWidth, fullFileName);
    }

    public bool ResizeImage(string fullFileName, int maxHeight, int maxWidth, string newFileName)
    {
        using (Image originalImage = Image.FromFile(fullFileName))
        {
            int height = originalImage.Height;
            int width = originalImage.Width;
            int newHeight = maxHeight;
            int newWidth = maxWidth;

            if (height > maxHeight || width > maxWidth)
            {
                if (height > maxHeight)
                {
                    newHeight = maxHeight;
                    float temp = ((float)width / (float)height) * (float)maxHeight;
                    newWidth = Convert.ToInt32(temp);

                    height = newHeight;
                    width = newWidth;
                }

                if (width > maxWidth)
                {
                    newWidth = maxWidth;
                    float temp = ((float)height / (float)width) * (float)maxWidth;
                    newHeight = Convert.ToInt32(temp);
                }

                Image.GetThumbnailImageAbort abort = new Image.GetThumbnailImageAbort(ThumbnailCallback);
                using (Image resizedImage = originalImage.GetThumbnailImage(newWidth, newHeight, abort, System.IntPtr.Zero))
                {
                    resizedImage.Save(newFileName);
                }

                return true;
            }
            else if (fullFileName != newFileName)
            {
                // no resizing necessary, but need to create new file 
                originalImage.Save(newFileName);
            }
        }

        return false;
    }

    private bool ThumbnailCallback()
    {
        return false;
    }
}
  • 0
    Он изменяет размер изображения с 1,8 МБ до 1 МБ при ширине всего 800 пикселей. Можно ли уменьшить размер файла?
  • 0
    Возможно, посмотрите на другие перегрузки метода Save. Msdn.microsoft.com/en-us/library/8ex6sdew(v=VS.100).aspx msdn.microsoft.com/en-us/library/ytz20d80(v=VS.100 ) .aspx
Показать ещё 1 комментарий
4

Я бы, конечно, не использовал GetThumbnailImage, поскольку это было бы шокирующим - для хорошего разрешения, не прибегая к DX или OpenL и т.д., я бы использовал что-то вроде следующего (из моей собственной графической библиотеки, которую я использую во многих приложениях для Windows - я поделился это несколько раз, прежде чем там могут быть варианты, плавающие вокруг сети). Здесь есть 3 метода: метод GetNonIndexedPixelFormat используется для остановки сбоя GDI при передаче форматов пикселей, которые он не может обрабатывать (комментарии объясняют это). Первый позволяет масштабировать с помощью коэффициента (Zoom), а последний позволяет фиксировать размерное масштабирование, сохраняя соотношение сторон (но его можно легко изменить, если вы хотите его перекосить). Наслаждайтесь:

    /// <summary>
    /// Scale Image By A Percentage - Scale Factor between 0 and 1.
    /// </summary>
    /// <param name="originalImg">Image: Image to scale</param>
    /// <param name="ZoomFactor">Float: Sclae Value - 0 to 1 are the usual values</param>
    /// <returns>Image: Scaled Image</returns>
    public static Image ScaleByPercent(Image originalImg, float ZoomFactor)
    {    
        int destWidth = (int)((float)originalImg.Width * ZoomFactor);
        int destHeight = (int)((float)originalImg.Height * ZoomFactor);

        Bitmap bmPhoto = new Bitmap(destWidth, destHeight, GetNonIndexedPixelFormat(originalImg)); // PixelFormat.Format24bppRgb);

        bmPhoto.SetResolution(originalImg.HorizontalResolution,  originalImg.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

        grPhoto.DrawImage(originalImg,
            new Rectangle(0, 0, destWidth, destHeight),
            new Rectangle(0, 0, originalImg.Width, originalImg.Height),
            GraphicsUnit.Pixel);

        grPhoto.Dispose();
        return bmPhoto;
    }

    /// <summary>
    /// Gets the closest non-indexed pixel format
    /// </summary>
    /// <param name="originalImage">Image: Original image</param>
    /// <returns>PixelFormat: Closest non-pixel image format</returns>
    public static PixelFormat GetNonIndexedPixelFormat(Image originalImage)
    {
        /*
         * These formats cause an error when creating a GDI Graphics Oblect, so must be converted to non Indexed
         * Error is "A graphics object cannot be created from an image that has an indexed pixel format"
         * 
            PixelFormat.Undefined 
            PixelFormat.DontCare 
            PixelFormat.1bppIndexed
            PixelFormat.4bppIndexed
            PixelFormat.8bppIndexed
            PixelFormat.16bppGrayScale
            PixelFormat.16bppARGB1555
         * 
         * An attempt is made to use the closest (i.e. smallest fitting) format that will hold the palette.
         */

        switch (originalImage.PixelFormat)
        {
            case PixelFormat.Undefined: 
                //This is also the same Enumation as PixelFormat.DontCare:
                return PixelFormat.Format24bppRgb;
            case PixelFormat.Format1bppIndexed:
                return PixelFormat.Format16bppRgb555;
            case PixelFormat.Format4bppIndexed:
                return PixelFormat.Format16bppRgb555;
            case PixelFormat.Format8bppIndexed:
                return PixelFormat.Format16bppRgb555;
            case PixelFormat.Format16bppGrayScale:
                return PixelFormat.Format16bppArgb1555;
            case PixelFormat.Format32bppArgb:
                return PixelFormat.Format24bppRgb;                
            default:
                return originalImage.PixelFormat;
        }
    }

    /// <summary>
    /// Resize image keeping aspect ratio.
    /// </summary>
    /// <param name="originalImg">Image: Image to scale</param>
    /// <param name="Width">Int: Required width in pixels</param>
    /// <param name="Height">Int: Required height in pixels</param>
    /// <param name="BackgroundColour">Color: Background colour</param>
    /// <returns>Image: Scaled Image</returns>
    public static Image Resize(Image originalImg, int Width, int Height, Color BackgroundColour)
    {
        int destX = 0;
        int destY = 0;

        float nPercent = 0f;

        float nPercentW = ((float)Width / (float)originalImg.Width);
        float nPercentH = ((float)Height / (float)originalImg.Height);

        if (nPercentH < nPercentW)
        {
            nPercent = nPercentH;
            destX = System.Convert.ToInt16(((float)Width - ((float)originalImg.Width * nPercent)) / 2f);
        }
        else
        {
            nPercent = nPercentW;
            destY = System.Convert.ToInt16(((float)Height - ((float)originalImg.Height * nPercent)) / 2f);
        }

        int destWidth = (int)(originalImg.Width * nPercent);
        int destHeight = (int)(originalImg.Height * nPercent);

        Bitmap bmPhoto = new Bitmap(Width, Height, GetNonIndexedPixelFormat(originalImg)); // PixelFormat.Format24bppRgb);

        bmPhoto.SetResolution(originalImg.HorizontalResolution, originalImg.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.Clear(BackgroundColour);
        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

        grPhoto.DrawImage(originalImg,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(0, 0, originalImg.Width, originalImg.Height), GraphicsUnit.Pixel);

        grPhoto.Dispose();
        return bmPhoto;
    }
  • 2
    +1 за сообщение о коде здесь, а не ссылку на внешний ресурс, срок действия которого может истечь. На самом деле ссылка в принятом ответе больше не работает. Спасибо.
2

Используйте Graphics.DrawImage(). GetThumbnailImage() вернет 120x120 (или меньше) встроенную миниатюру из файла jpeg. Это будет ужасно для чего-либо выше этого размера.

См. http://nathanaeljones.com/163/20-image-resizing-pitfalls/ для использования соответствующих параметров.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню