【问题标题】:make thumbnail from database image while keeping aspect ratio从数据库图像制作缩略图,同时保持纵横比
【发布时间】:2012-12-20 17:23:34
【问题描述】:

我已将图像存储在 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

【问题讨论】:

  • 您读取当前尺寸,进行一些计算,然后创建新尺寸。
  • 我知道,但是如何读取当前大小?这是我的主要问题
  • 保存图像的loBMP(来自您的代码)具有loBMP.WidthloBMP.Height,即图像的大小。
  • 谢谢它的工作,但我的缩略图太大了!它比原始图像还要大,它是 PNG 格式,我想要一个小尺寸的图像(以磁盘上的字节计),我的图像宽度和高度减小了,但它的磁盘大小更大
  • 查看以下 koste 的答案,并使用此计算来制作最终的缩略图大小。

标签: asp.net sql-server image


【解决方案1】:

这可能对你有帮助:

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;
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      相关资源
      最近更新 更多