出于安全性能的考虑,目前js端不支持获取本地图片进行预览,正好在做一款类似于QQ心情的发布框,找了不少jquery插件,没几个能满足需求,因此自己使用SWFuplad来实现这个图片上传预览。
public class Thumbnial
{
///
/// 生成缩略图
/// ///
原图片
///
缩略图宽度
///
缩略图高度
///
是否裁剪(以中心点)
///
public static Image GetThumbnail(System.Drawing.Image imgSource, int newWidth, int newHeight, bool isCut)
{
int rWidth = 0; // 等比例缩放后的宽度
int rHeight = 0; // 等比例缩放后的高度
int sWidth = imgSource.Width; // 原图片宽度
int sHeight = imgSource.Height; // 原图片高度
double wScale = (double)sWidth / newWidth; // 宽比例
double hScale = (double)sHeight / newHeight; // 高比例
double scale = wScale < hScale ? wScale : hScale;
rWidth = (int)Math.Floor(sWidth / scale);
rHeight = (int)Math.Floor(sHeight / scale);
Bitmap thumbnail = new Bitmap(rWidth, rHeight);
try
{
// 如果是截取原图,并且原图比例小于所要截取的矩形框,那么保留原图
if (!isCut && scale <= 1)
{
return imgSource;
}
using (Graphics tGraphic = Graphics.FromImage(thumbnail))
{
tGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */
Rectangle rect = new Rectangle(0, 0, rWidth, rHeight);
Rectangle rectSrc = new Rectangle(0, 0, sWidth, sHeight);
tGraphic.DrawImage(imgSource, rect, rectSrc, GraphicsUnit.Pixel);
}
if (!isCut)
{
return thumbnail;
}
else
{
int xMove = 0; // 向右偏移(裁剪)
int yMove = 0; // 向下偏移(裁剪)
xMove = (rWidth - newWidth) / 2;
yMove = (rHeight - newHeight) / 2;
Bitmap final_image = new Bitmap(newWidth, newHeight);
using (Graphics fGraphic = Graphics.FromImage(final_image))
{
fGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */
Rectangle rect1 = new Rectangle(0, 0, newWidth, newHeight);
Rectangle rectSrc1 = new Rectangle(xMove, yMove, newWidth, newHeight);
fGraphic.DrawImage(thumbnail, rect1, rectSrc1, GraphicsUnit.Pixel);
}
thumbnail.Dispose();
return final_image;
}
}
catch (Exception e)
{
return new Bitmap(newWidth, newHeight);
}
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Mood.aspx.cs" Inherits="Mood.Mood" %>
使用Vs2010开发,以下为项目源码地址