生成整齐,美观的缩略图

需求:电子商务中有大量的图片要丰前台显示,而这些图片大部分由客户自己上传,图片的规格也是多种多样(主要择时纵横比例)。怎样让这些图片在前台整齐且美观的显示呢?

目的:整齐:固定纵横比例;美观:图片不变型,也就是按比例缩放。

假设:假如我们要在前台的一个Div(别名:相框)中放一张图(别名:图A),相框的宽度为120px,高度为:90px。而图A的原图的宽度为为1414px,高度为:886px.
显然相框与图A的原图的比例不一致。为了整齐且美观,我们希望将图A处理成56*96.然后把她居中的放在相框(120*90)中。

方案:我们采用.net技术,通过GDI操作图片:

实施:不想多说(相信博友们都应该看得懂)先贴出我的图像处理类(注释还算清楚):

using System;
using System.Drawing;
using System.IO;

namespace Ants.Tools
{
    
public class Image
    
{
        
属性

        
private bool ThumbnailCallBack()//GDI+委托
        {
            
return false;
        }

        
/// <summary>
        
/// 缩略图片的函数
        
/// </summary>
        
/// <param name="OK">用来判断转换是否成功</param>
        
/// <returns>处理好的图片缩略图放入内存中</returns>

        public MemoryStream getThumb(out bool OK)
        
{
            OK
=false;
            
int X, Y;
            System.Drawing.Image myThumbnail 
= null;
            
try
            
{
                Bitmap myBitmap 
= new Bitmap(Path);
                X 
= myBitmap.Width;
                Y 
= myBitmap.Height;
                
decimal a = (decimal)X / (decimal)Y;//原图片的比例
                decimal b = (decimal)Width / (decimal)Height;//相框的比例
                System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallBack);
                
                
int newheight, newwidth;
                
if (b > a)
                
{
                    newheight 
= Height;
                    newwidth 
=(intdecimal.Round(newheight * a,0,MidpointRounding.AwayFromZero);
                }

                
else
                
{
                    newwidth 
= Width;
                    newheight 
= (int)decimal.Round(Width / a, 0, MidpointRounding.AwayFromZero);

                }

                myThumbnail 
= myBitmap.GetThumbnailImage(newwidth, newheight, myCallBack, IntPtr.Zero);//生成缩略图
               OK=true;
               myBitmap.Dispose();               
            }

            
catch
            
{
                OK
= false;
            }

            System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
            myThumbnail.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
          
            
return ms;
        }

    }

}


如何应用此类呢?还是贴代码:
1.新建一个aspx页面,放一个<img>标签
代码如下:

Code


2.再建一个ashx文件
代码如下:

Code


生成的效果如下

那张图和比例也太过分啦。呵呵...,欢迎

原文地址:https://www.cnblogs.com/leleroyn/p/1231039.html