在保持纵横比的同时从数据库图像制作缩略图

时间:2012-12-20 17:23:34

标签: asp.net sql-server image

我已将我的图像存储在SQL server中,而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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

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

它可以让你自己做你正在做的事情并自动处理宽高比。