使用 Stream 重新改變圖片大小(等比縮放)

  • 12418
  • 0

使用 Stream 重新改變圖片大小(等比縮放)

在做asp.net使用泛型處理常式(Generic Handler *.ashx)時輸出圖片,

就可用來做到等比縮放的圖片產生!


    /// 重新改變圖片大小
    /// </summary>
    /// <param name="BitmapStream">原始圖片串流</param>
    /// <param name="lnWidth">希望寬度範圍</param>
    /// <param name="lnHeight">希望高度範圍</param>
    /// <returns>長寬改變後的新圖片</returns>
    public static Bitmap CreateThumbnail(Stream BitmapStream, int lnWidth, int lnHeight)
    {

        System.Drawing.Bitmap bmpOut = null;
        try
        {
            Bitmap loBMP = new Bitmap(BitmapStream);
            System.Drawing.Imaging.ImageFormat loFormat = loBMP.RawFormat;
            decimal lnRatio;
            int lnNewWidth = 0;
            int lnNewHeight = 0;

            //*** If the image is smaller than a thumbnail just return it
            if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
                return loBMP;

            if (loBMP.Width > loBMP.Height)
            {
                lnRatio = (decimal)lnWidth / loBMP.Width;
                lnNewWidth = lnWidth;
                decimal lnTemp = loBMP.Height * lnRatio;
                lnNewHeight = (int)lnTemp;
            }
            else
            {
                lnRatio = (decimal)lnHeight / loBMP.Height;
                lnNewHeight = lnHeight;
                decimal lnTemp = loBMP.Width * lnRatio;
                lnNewWidth = (int)lnTemp;
            }

            // System.Drawing.Image imgOut = 
            //      loBMP.GetThumbnailImage(lnNewWidth,lnNewHeight,
            //                              null,IntPtr.Zero);
            // *** This code creates cleaner (though bigger) thumbnails and properly
            // *** and handles GIF files better by generating a white background for
            // *** transparent images (as opposed to black)

            bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
            Graphics g = Graphics.FromImage(bmpOut);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
            g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);

            loBMP.Dispose();
        }
        catch
        {
            return null;
        }
        return bmpOut;
    }

使用方式:


MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["XXX"]);
Bitmap bmp = CreateThumbnail((Stream)ms, 200, 200);