0

我已经将我的图像存储在 SQL 服务器中,并且 imageContent 是一个字节数组(其中包含存储在 DB 中的图像数据)。我使用以下代码从我的主图像创建缩略图,目前我为我的缩略图(40x40)设置了明确的宽度和高度,但它会损坏我的图像纵横比,我怎样才能找到原始图像的纵横比并缩小它所以我原来的纵横比没有改变?

            Stream str = new MemoryStream((Byte[])imageContent);
        Bitmap loBMP = new Bitmap(str);
        Bitmap bmpOut = new Bitmap(40, 40);
        Graphics g = Graphics.FromImage(bmpOut);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.FillRectangle(Brushes.White, 0, 0, 40, 40);
        g.DrawImage(loBMP, 0, 0, 40, 40);
        MemoryStream ms = new MemoryStream();
        bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        byte[] bmpBytes = ms.GetBuffer();
        bmpOut.Dispose();
        //end new

        Response.ContentType = img_type;
        Response.BinaryWrite(bmpBytes);//imageContent,bmpBytes
4

2 回答 2

2

可能这可以帮助你:

public static Bitmap CreateThumbnail(Bitmap source, int thumbWidth, int thumbHeight, bool maintainAspect)
{
        if (source.Width < thumbWidth && source.Height < thumbHeight) return source;

        Bitmap image = null;
        try
        {
            int width = thumbWidth;
            int height = thumbHeight;

            if (maintainAspect)
            {
                if (source.Width > source.Height)
                {
                    width = thumbWidth;
                    height = (int)(source.Height * ((decimal)thumbWidth / source.Width));
                }
                else
                {
                    height = thumbHeight;
                    width = (int)(source.Width * ((decimal)thumbHeight / source.Height));
                }
            }

            image = new Bitmap(width, height);
            using (Graphics g = Graphics.FromImage(image))
            {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.FillRectangle(Brushes.White, 0, 0, width, height);
                g.DrawImage(source, 0, 0, width, height);
            }

            return image;
        }
        catch
        {
            image = null;
        }
        finally
        {
            if (image != null)
            {
                image.Dispose();
            }
        }

        return null;
}
于 2012-12-20T17:48:05.943 回答
1

看看 ImageResizer 项目:http: //imageresizing.net/

它允许您做您正在做的事情并自动为您处理纵横比。

于 2012-12-20T17:26:43.847 回答