2

大画像とサムネイル画像の 2 つのサイズの画像を保存する画像アップロード フォームがあります。

サムネイル画像については、画像を中央から切り取り、サイズを 30px x 30px に変更しようとしています。

これが私のコードです:

    private static Bitmap ResizeImage(MemoryStream uploadStream, int maxWidth, int maxHeight)
    {
        Image img = Image.FromStream(uploadStream);

        double ratioX = (double)maxWidth / img.Width;
        double ratioY = (double)maxHeight / img.Height;
        double ratio = Math.Max(ratioX, ratioY);

        int newWidth = (int)(img.Width * ratio);
        int newHeight = (int)(img.Height * ratio);

        Bitmap resizedBitmap = new Bitmap(newWidth, newHeight);
        Graphics.FromImage(resizedBitmap).DrawImage(img, 0, 0, newWidth, newHeight);

        img.Dispose();

        return resizedBitmap;
    }

    private static Bitmap CropImageToCentre(MemoryStream uploadStream, int width, int height)
    {
        Image img = Image.FromStream(uploadStream);
        Bitmap resizedBitmap = new Bitmap(img); 

        int StartX = 0, StartY = 0;
        int EndX = img.Width, EndY = img.Height;
        bool Crop = false;

        if (img.Width > width)
        {
            int MidX = img.Width / 2;
            StartX = MidX - (width / 2);
            EndX = MidX + (width / 2);
            Crop = true;
        }

        if (img.Width > height)
        {
            int MidY = img.Height / 2;
            StartY = MidY - (height / 2);
            EndY = MidY + (height / 2);
            Crop = true;
        }

        if (Crop)
        {
            Size imgSize = new Size(width, height);
            resizedBitmap = new Bitmap(img, imgSize);
        }

        img.Dispose();

        return resizedBitmap;
    }

    public static Bitmap ResizeThumbnail(MemoryStream ms)
    {
        int thumbWidth = int.Parse(ConfigurationManager.AppSettings["thumbwidth"]);
        int thumbHeight = int.Parse(ConfigurationManager.AppSettings["thumbheight"]);

        return CropImageToCentre(BitmapToMemoryStream(ResizeImage(ms, thumbWidth, thumbHeight)), thumbWidth, thumbHeight);
    }

    public static Bitmap ResizeLargeImage(MemoryStream ms)
    {
        int width = int.Parse(ConfigurationManager.AppSettings["largewidth"]);
        int height = int.Parse(ConfigurationManager.AppSettings["largeheight"]);

        return ResizeImage(ms, width, height);
    }

    private static MemoryStream BitmapToMemoryStream(Bitmap bm)
    {
        MemoryStream memoryStream = new MemoryStream();
        bm.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);

        return memoryStream;
    }

私が抱えている問題は、ResizeThumbnail()メソッドを呼び出すときに、画像が切り取られたり、高さと幅が 30 ピクセルにサイズ変更されなかったりすることです。

4

2 に答える 2