很多网站都会让用户上传图片作为头像,可是用户的照片大小不一,所以现在网上的很流行的做法就是可以支持上传图片时让用户动态裁剪大小,但是基本上都是Flash 实现的,本人不会Flash,所以用SilverLight 做了一个组件,其中,前台在点击上传时候,会弹出一个PopUp控件,用户存放上传照片和实现裁剪。
实现原理:
上传一个照片到一个滚动区域中,然后在这个滚动区域中加一个GRID,设置它MouseMove事件的发生坐标系来实现拖拽功能,在每次停止拖放的时候保存框框相对于图片左上角的坐标,把这个坐标传到后台 Ashx文件中,用GDI+ 来找到该图片相应裁剪区域的像素,画成新图片
实现效果:
前台弹出框的 xaml:
<Popup Width="600" Height="300" HorizontalAlignment="Left" VerticalAlignment="Top" x:Name="Pop_selectpic" HorizontalOffset="20" VerticalOffset="50" IsOpen="False">
<Border Height="300" Width="600" BorderThickness="1,1,1,1" HorizontalAlignment="Left" VerticalAlignment="Top" Background="{x:Null}">
<Border.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFEBEBEB"/>
<GradientStop Color="#FF434390" Offset="1"/>
</LinearGradientBrush>
</Border.BorderBrush>
<Grid Height="300" Width="600" HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF000000"/>
<GradientStop Color="#FF434390" Offset="1"/>
<GradientStop Color="#FFEBEBEB" Offset="0.76499998569488525"/>
</LinearGradientBrush>
</Grid.Background>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400*"/>
<ColumnDefinition Width="200*"/>
</Grid.ColumnDefinitions>
<Button Margin="20,150,0,0" Grid.Column="1" VerticalAlignment="Top" Height="30" HorizontalAlignment="Left" Width="150" Click="Button_Click_4">
<ContentControl HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid HorizontalAlignment="Left" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Top">
<Image Source="../Images/tupian.png" Width="18" Height="16" />
<TextBlock Text="Select your photo" TextWrapping="Wrap" Foreground="#FF434390" Width="100" HorizontalAlignment="Left" VerticalAlignment="Top" TextAlignment="Center"/>
</StackPanel>
</Grid>
</ContentControl>
</Button>
<Button VerticalAlignment="Top" Grid.Column="1" Margin="20,200,0,0" Width="150" Height="30" HorizontalAlignment="Left" Click="Button_Click_3">
<ContentControl HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Top">
<Image Height="17" Width="17" Source="../Images/savep.png"/>
<TextBlock Text="Save" TextWrapping="Wrap" Foreground="#FF434390" HorizontalAlignment="Left" VerticalAlignment="Top" Width="50" TextAlignment="Center"/>
</StackPanel>
</Grid>
</ContentControl>
</Button>
<Button VerticalAlignment="Top" Grid.Column="1" Margin="20,250,0,0" Width="150" Height="30" HorizontalAlignment="Left" Click="Button_Click_2" >
<ContentControl HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Top">
<Image Height="17" Width="17" Source="../Images/closep.png" />
<TextBlock Text="Close" TextWrapping="Wrap" Foreground="#FF434390" Width="50" TextAlignment="Center"/>
</StackPanel>
</Grid>
</ContentControl>
</Button>
<Grid Height="100" VerticalAlignment="Top" Grid.Column="1" Margin="40,25,80,0" HorizontalAlignment="Left" Width="100">
<Image Height="Auto" VerticalAlignment="Center" x:Name="img_yulan" HorizontalAlignment="Center"/>
</Grid>
<Grid MaxWidth="Infinity" MinHeight="90" MinWidth="68" x:Name="grid_temp" Margin="10,10,40,40" RenderTransformOrigin="0.5,0.5" Width="350" Height="250" HorizontalAlignment="Left" VerticalAlignment="Top" >
<Grid.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Grid.RenderTransform>
<ScrollViewer Height="250" HorizontalAlignment="Left" VerticalAlignment="Top" Width="350" Padding="0,0,0,0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" x:Name="scrollviewer1" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
<ContentControl.RenderTransform>
<ScaleTransform x:Name="ScaleTforFaceScrollViewer"></ScaleTransform>
</ContentControl.RenderTransform>
<Grid Height="Auto" Width="Auto" x:Name="grid6">
<Grid.RenderTransform>
<TransformGroup>
<ScaleTransform x:Name="ScaleTforFaceGrid"/>
</TransformGroup>
</Grid.RenderTransform>
<Image Height="Auto" Width="Auto" x:Name="img_temp" HorizontalAlignment="Left" VerticalAlignment="Top">
<Image.RenderTransform>
<TransformGroup x:Name="TGforFaceImage">
<ScaleTransform x:Name="ScaleTforFaceImage"/>
<SkewTransform x:Name="SkewTforFaceImage"/>
<RotateTransform x:Name="RotateTforFaceImage"/>
<TranslateTransform x:Name="TranslateTforFaceImage"/>
</TransformGroup>
</Image.RenderTransform>
</Image>
</Grid>
</ScrollViewer>
<Popup HorizontalAlignment="Left" Margin="0,0,0,0" Width="68" VerticalAlignment="Top" Height="90" x:Name="pop2" >
<Border Height="90" Width="68" BorderThickness="2,2,2,2" HorizontalAlignment="Left" VerticalAlignment="Top">
<Border.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF000000"/>
<GradientStop Color="#FF434390" Offset="1"/>
</LinearGradientBrush>
</Border.BorderBrush>
<Grid Height="90" Width="68" Opacity="0.2" Background="White" MouseMove="Border_MouseMove" MouseLeftButtonDown="Grid_MouseLeftButtonDown" MouseLeftButtonUp="Grid_MouseLeftButtonUp" Cursor="Stylus" RenderTransformOrigin="0.5,0.5">
<Grid.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Grid.RenderTransform>
</Grid>
</Border>
</Popup>
</Grid>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Bottom" Text="Size :" TextWrapping="Wrap" Margin="30,0,0,8" Foreground="#FFFFFFFF"/>
<Slider VerticalAlignment="Bottom" Height="20" Margin="91,0,109,6" Maximum="10" SmallChange="0.1" Minimum="0.1" IsDirectionReversed="False" Value="1" LargeChange="0.1" ValueChanged="Slider_ValueChanged" x:Name="slider" MouseLeftButtonUp="slider_MouseLeftButtonUp" />
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Bottom" Text="x 1" TextWrapping="Wrap" Margin="295,0,0,8" Width="115" x:Name="tbl_value" Foreground="#FFFFFFFF"/>
<Canvas Height="44" Margin="30,105,50,0" VerticalAlignment="Top" Canvas.ZIndex="1" x:Name="Canvas_progressbar" Visibility="Collapsed">
<ProgressBar Height="15" Width="320" Canvas.Top="20" x:Name="progressbar1" IsIndeterminate="True"/>
<TextBlock Width="72" Canvas.Left="3" Text="Loading..." TextWrapping="Wrap" Foreground="#FF808080"/>
</Canvas>
</Grid>
</Border>
</Popup>
后台代码:
#region 上传照片
//edit
private void TextBlock_MouseLeftButtonUp_2(object sender, MouseButtonEventArgs e)
{
Pop_selectpic.IsOpen = true;
}
//clear
private void TextBlock_MouseLeftButtonUp_4(object sender, MouseButtonEventArgs e)
{
this.photosrc = "";
this.Img_Photo.Source = new BitmapImage(new Uri("../Images/Rlogo.png", UriKind.Relative));
this.Img_Photo_2.Source = new BitmapImage(new Uri("../Images/Rlogo.png", UriKind.Relative));
}
private void UploadFile_2(string fileName, Stream data)
{
fileData = data;
// 取得泛型处理常式的绝对 URL 。
UriBuilder ub = new UriBuilder(GetAbsoluteUrl("Handler_TakeUploadFile.ashx"));
// 替泛型处理常式的绝对 URL 加上查询字串。
ub.Query = string.Format("FileName={0}&FileLength={1}&Pic=photo", HttpUtility.UrlEncode(fileName), fileData.Length);
WebClient wc = new WebClient();
wc.OpenWriteCompleted += wc_OpenWriteCompleted_2;
wc.OpenWriteAsync(ub.Uri);
wc.WriteStreamClosed += wc_WriteStreamClosed_2;
}
void wc_WriteStreamClosed_2(object sender, WriteStreamClosedEventArgs e)
{
this.img_temp.Source = new BitmapImage(new Uri("../TempFile/" + tempsrc, UriKind.Relative));
pop2.IsOpen = true;
pop2.HorizontalOffset = 0.0;
pop2.VerticalOffset = 0.0;
this.Canvas_progressbar.Visibility = Visibility.Collapsed;
if (tempsrc != "")
{
yulansrc = Guid.NewGuid() + "." + tempsrc.Split('.')[1];
WebClient mywc = new WebClient();
mywc.OpenReadCompleted += new OpenReadCompletedEventHandler(mywc_OpenReadCompleted);
mywc.OpenReadAsync(new Uri(string.Format(GetAbsoluteUrl("Handler_GetTempPic.ashx?filename={0}&ysrc={1}&Ho={2}&Yo={3}&sca={4}&rd=" + this.RndNum(4)), HttpUtility.UrlEncode(tempsrc), HttpUtility.UrlEncode(yulansrc), HttpUtility.UrlEncode((pop2.HorizontalOffset+this.scrollviewer1.HorizontalOffset+2).ToString()), HttpUtility.UrlEncode((pop2.VerticalOffset+this.scrollviewer1.VerticalOffset+2).ToString()), HttpUtility.UrlEncode(slider.Value.ToString())), UriKind.Absolute));
}
}
private void wc_OpenWriteCompleted_2(object sender, OpenWriteCompletedEventArgs e)
{
byte[] buffer = new byte[fileData.Length + 1];
int bytesRead = 0;
bytesRead = fileData.Read(buffer, 0, buffer.Length);
while (bytesRead != 0)
{
e.Result.Write(buffer, 0, bytesRead);
bytesRead = fileData.Read(buffer, 0, buffer.Length);
}
e.Result.Close();
fileData.Close();
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
this.Reset();
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
mousedown = false;
if (yulansrc != "")
{
//yulansrc = Guid.NewGuid() + "." + tempsrc.Split('.')[1];
WebClient mywc = new WebClient();
mywc.OpenReadCompleted += new OpenReadCompletedEventHandler(mywc_OpenReadCompleted_1);
mywc.OpenReadAsync(new Uri(string.Format(GetAbsoluteUrl("Handler_Copy.ashx?filename={0}&rd=" + this.RndNum(4)), HttpUtility.UrlEncode(yulansrc)), UriKind.Absolute));
}
}
private void Button_Click_4(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
// 设定能显示在开启文件对话方块中的文件类型。
openFileDialog1.Filter = "图像文件(.jpg, .png,.jpeg,.jpe)|*.jpg;*.png;*.jpeg;*.jpe";
openFileDialog1.FilterIndex = 2;
// 只能选择一个文件
openFileDialog1.Multiselect = false;
// 呼叫 ShowDialog 方法来显示出开启文件对话方块。
bool? userClickedOK = openFileDialog1.ShowDialog();
// 如果使用者按下“确定”按钮则继续处理。
if (userClickedOK.GetValueOrDefault() == true)
{
if (openFileDialog1.File.Length > 10240000)
{
//System.Windows.Browser.HtmlPage.Window.Alert(openFileDialog1.File.Length.ToString());
System.Windows.Browser.HtmlPage.Window.Alert("You picture is too large, please select another one.");
return;
}
else
{
this.Canvas_progressbar.Visibility = Visibility.Visible;
tempsrc = Guid.NewGuid() + System.IO.Path.GetExtension(openFileDialog1.File.Name);
UploadFile_2(tempsrc, openFileDialog1.File.OpenRead());
}
}
else
{
//MessageBox.Show("您没有选择所要上传的文件", "请注意", MessageBoxButton.OK);
}
}
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
mousedown = true;
}
private void Grid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
mousedown = false;
if (tempsrc != "")
{
yulansrc = Guid.NewGuid() + "." + tempsrc.Split('.')[1];
WebClient mywc = new WebClient();
mywc.OpenReadCompleted += new OpenReadCompletedEventHandler(mywc_OpenReadCompleted);
mywc.OpenReadAsync(new Uri(string.Format(GetAbsoluteUrl("Handler_GetTempPic.ashx?filename={0}&ysrc={1}&Ho={2}&Yo={3}&sca={4}&rd=" + this.RndNum(4)), HttpUtility.UrlEncode(tempsrc), HttpUtility.UrlEncode(yulansrc), HttpUtility.UrlEncode((pop2.HorizontalOffset+this.scrollviewer1.HorizontalOffset+2).ToString()), HttpUtility.UrlEncode((pop2.VerticalOffset+this.scrollviewer1.VerticalOffset+2).ToString()), HttpUtility.UrlEncode(slider.Value.ToString())), UriKind.Absolute));
}
}
void mywc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
this.img_yulan.Source = new BitmapImage(new Uri("../TempFile2/" + yulansrc, UriKind.Relative));
}
void mywc_OpenReadCompleted_1(object sender, OpenReadCompletedEventArgs e)
{
this.photosrc = yulansrc;
this.Img_Photo.Source = new BitmapImage(new Uri("../Img/" + photosrc, UriKind.Relative));
this.Img_Photo_2.Source = new BitmapImage(new Uri("../Img/" + photosrc, UriKind.Relative));
this.Reset();
}
private void Border_MouseMove(object sender, MouseEventArgs e)//拖放裁剪框
{
FrameworkElement element = sender as FrameworkElement;
if (mousedown)
{
double deltaV;
double deltaH;
if (pot != new Point(0, 0))
{
deltaV = e.GetPosition(grid_temp).Y - pot.Y;
deltaH = e.GetPosition(grid_temp).X - pot.X;
}
else
{
deltaV = 0.0;
deltaH = 0.0;
}
pop2.Opacity = 0.5;
pop2.HorizontalOffset += deltaH;
pop2.VerticalOffset += deltaV;
if (pop2.HorizontalOffset > grid_temp.Width - pop2.Width)
{
pop2.HorizontalOffset = grid_temp.Width - pop2.Width;
// mousedown = false;
}
//else if (pop2.HorizontalOffset > (scrollviewer1.Width + scrollviewer1.HorizontalOffset - pop2.Width))
//{
// pop2.HorizontalOffset = (scrollviewer1.Width + scrollviewer1.HorizontalOffset - pop2.Width);
// mousedown = false;
//}
//else if (pop2.HorizontalOffset < scrollviewer1.HorizontalOffset)
//{
// pop2.HorizontalOffset = scrollviewer1.HorizontalOffset;
// mousedown = false;
//}
if (pop2.VerticalOffset > grid_temp.Height - pop2.Height)
{
pop2.VerticalOffset = grid_temp.Height - pop2.Height;
//mousedown = false;
}
//else if (pop2.VerticalOffset > (scrollviewer1.Height + scrollviewer1.VerticalOffset - pop2.Height))
//{
// pop2.VerticalOffset = (scrollviewer1.Height + scrollviewer1.VerticalOffset - pop2.Height);
// mousedown = false;
//}
//else if (pop2.VerticalOffset < scrollviewer1.VerticalOffset)
//{
// pop2.VerticalOffset = scrollviewer1.VerticalOffset;
// mousedown = false;
//}
if (pop2.HorizontalOffset < 0)
{
pop2.HorizontalOffset = 0;
//mousedown = false;
}
if (pop2.VerticalOffset < 0)
{
pop2.VerticalOffset = 0;
//mousedown = false;
}
pot = e.GetPosition(grid_temp);
}
}
private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)//缩放图片
{
try
{
this.ScaleTforFaceImage.ScaleX = e.NewValue;//缩放图片
this.ScaleTforFaceImage.ScaleY = e.NewValue;
this.tbl_value.Text = "x " + e.NewValue.ToString("0.0000");
}
catch (Exception ex)
{
ex.ToString();
}
}
public void Reset()
{
Pop_selectpic.IsOpen = false;
pop2.VerticalOffset = 0;
pop2.HorizontalOffset = 0;
this.slider.Value = 1;
this.yulansrc = "";
this.tempsrc = "";
img_temp.ClearValue(Image.SourceProperty);
img_yulan.ClearValue(Image.SourceProperty);
pop2.IsOpen = false;
}
private void slider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (tempsrc != "")
{
yulansrc = Guid.NewGuid() + "." + tempsrc.Split('.')[1];
WebClient mywc = new WebClient();
mywc.OpenReadCompleted += new OpenReadCompletedEventHandler(mywc_OpenReadCompleted);
mywc.OpenReadAsync(new Uri(string.Format(GetAbsoluteUrl("Handler_GetTempPic.ashx?filename={0}&ysrc={1}&Ho={2}&Yo={3}&sca={4}&rd=" + this.RndNum(4)), HttpUtility.UrlEncode(tempsrc), HttpUtility.UrlEncode(yulansrc), HttpUtility.UrlEncode((pop2.HorizontalOffset+scrollviewer1.HorizontalOffset).ToString()), HttpUtility.UrlEncode((pop2.VerticalOffset+scrollviewer1.VerticalOffset).ToString()), HttpUtility.UrlEncode(slider.Value.ToString())), UriKind.Absolute));//把裁剪参数传到ashx 文件中,实现裁剪
}
}
#endregion
ashx 文件:
1,上传图片:
<%@ WebHandler Language="C#" Class="TakeUploadFile" %>
using System;
using System.Web;
using System.IO;
using System.Xml;
using System.Drawing;
public class TakeUploadFile : IHttpHandler {
private int FileLength;
public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/xml; charset=utf-8";
// context.Response.AddHeader("ContentType", "text/xml; charset=utf-8");
//XmlTextWriter xmlWriter = new XmlTextWriter(context.Response.Output);
try
{
string filename = context.Request.QueryString["FileName"].ToString();
FileLength = System.Convert.ToInt32(context.Request.QueryString["FileLength"]);
string pic= context.Request.QueryString["Pic"].ToString();
using (FileStream fs = File.Create(context.Server.MapPath("~/ClientBin/TempFile/" + filename)))
{
SaveFile(context.Request.InputStream, fs);
fs.Close();
Image img = Image.FromFile(context.Server.MapPath("~/ClientBin/TempFile/" + filename));
if (pic == "logo")
{
//如果长宽比大于 100比50 则按高为50缩图
if ((Convert.ToDouble(img.Width) / Convert.ToDouble(img.Height)) <= (100 / 50))
{
int height = 50;
int width = img.Width * 50 / img.Height;
Image img2 = img.GetThumbnailImage(width, height, new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
img2.Save(context.Server.MapPath("~/ClientBin/Img/" + filename));
}
else//如果长宽比小于 100比50 则按宽为100缩图
{
int width = 100;
int height = img.Height * 100 / img.Width;
Image img2 = img.GetThumbnailImage(width, height, new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
img2.Save(context.Server.MapPath("~/ClientBin/Img/" + filename));
}
}
else if (pic == "photo")
{
//如果长宽比小于 68比90 则按高为90缩图
if ((Convert.ToDouble(img.Width) / Convert.ToDouble(img.Height)) <= (Convert.ToDouble(68) /Convert.ToDouble(90)))
{
int height = 90;
int width = img.Width * 90 / img.Height;
Image img2 = img.GetThumbnailImage(width, height, new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
Image img3 = img.GetThumbnailImage(width*(40/68), height*(55/90), new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
img2.Save(context.Server.MapPath("~/ClientBin/Img/" + filename));
img3.Save(context.Server.MapPath("~/ClientBin/SImg/" + filename));
}
else//如果长宽比不小于 68比90 则按宽为90缩图
{
int width = 68;
int height = img.Height * 68 / img.Width;
Image img2 = img.GetThumbnailImage(width, height, new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
Image img3 = img.GetThumbnailImage(width * (40 / 68), height * (55 / 90), new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
img2.Save(context.Server.MapPath("~/ClientBin/Img/" + filename));
img3.Save(context.Server.MapPath("~/ClientBin/SImg/" + filename));
}
//如果长宽比小于 40比55 则按高为55缩图
//if ((Convert.ToDouble(img.Width) / Convert.ToDouble(img.Height)) <= (Convert.ToDouble(68) / Convert.ToDouble(90)))
//{
// int height = 55;
// int width = img.Width * 55 / img.Height;
// Image img2 = img.GetThumbnailImage(width, height, new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
// //Image img3 = img.GetThumbnailImage(width * (40 / 68), height * (55 / 90), new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
// img2.Save(context.Server.MapPath("~/ClientBin/SImg/" + filename));
// //img3.Save(context.Server.MapPath("~/ClientBin/SImg/" + filename));
//}
//else//如果长宽比不小于 40比55 则按宽为90缩图
//{
// int width = 40;
// int height = img.Height * 40 / img.Width;
// Image img2 = img.GetThumbnailImage(width, height, new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
// //Image img3 = img.GetThumbnailImage(width * (40 / 68), height * (55 / 90), new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
// img2.Save(context.Server.MapPath("~/ClientBin/SImg/" + filename));
// //img3.Save(context.Server.MapPath("~/ClientBin/SImg/" + filename));
//}
}
else if (pic == "ListLogo")
{
//如果长宽比小于 80比100 则按高为100缩图
if ((Convert.ToDouble(img.Width) / Convert.ToDouble(img.Height)) <= (Convert.ToDouble(80) / Convert.ToDouble(100)))
{
int height = 100;
int width = img.Width * 100 / img.Height;
Image img2 = img.GetThumbnailImage(width, height, new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
img2.Save(context.Server.MapPath("~/ClientBin/Img/" + filename));
}
else//如果长宽比小于 80比100 则按宽为80缩图
{
int width = 80;
int height = img.Height * 80 / img.Width;
Image img2 = img.GetThumbnailImage(width, height, new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
img2.Save(context.Server.MapPath("~/ClientBin/Img/" + filename));
}
}
}
}
catch(Exception ex)
{
ex.ToString();
}
}
private void SaveFile(Stream stream, FileStream fs)
{
byte[] buffer = new byte[FileLength + 1];
int bytesRead = 0;
bytesRead = stream.Read(buffer, 0, buffer.Length);
while (bytesRead != 0)
{
fs.Write(buffer, 0, bytesRead);
bytesRead = stream.Read(buffer, 0, buffer.Length);
}
}
public bool IsReusable {
get {
return false;
}
}
private bool Abort()
{
return false;
}
}
2,裁剪图片
<%@ WebHandler Language="C#" Class="Handler_GetTempPic" %>
using System;
using System.Web;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.ComponentModel;
using System.Drawing;
using System.Xml;
using System.IO;
public class Handler_GetTempPic : IHttpHandler {
public void ProcessRequest (HttpContext context) {
try
{
//filename={0}&ysrc={1}&Ho={2}&Yo={3}&sca={4}
string filename1 = HttpContext.Current.Request.QueryString["filename"];
string filename2 = HttpContext.Current.Request.QueryString["ysrc"];
double x = Convert.ToDouble(HttpContext.Current.Request.QueryString["HO"]);
double y = Convert.ToDouble(HttpContext.Current.Request.QueryString["YO"]);
double sca = Convert.ToDouble(HttpContext.Current.Request.QueryString["sca"]);
Image img = Image.FromFile(context.Server.MapPath("~/ClientBin/TempFile/" + filename1));
Image img2 = img.GetThumbnailImage( Convert.ToInt32(img.Width*sca),Convert.ToInt32(img.Height*sca), new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero);
//img2.Save(context.Server.MapPath("~/ClientBin/TempFile/" + filename2));
Graphics graphics;
Bitmap bmp = new Bitmap(68,90);
graphics = Graphics.FromImage(bmp);
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;//定义画笔质量
Bitmap MyBitmapSource = (Bitmap)(img2);
for (int i = 0; i < 68; i++)
{
for (int j = 0; j < 90; j++)
{
if (((int)x<0)||((int)y<0))
{
bmp.SetPixel(i, j, Color.Gray);
}
else if (((int)x + i) < MyBitmapSource.Width && ((int)y + j) < MyBitmapSource.Height)
{
Color MyColor = MyBitmapSource.GetPixel((int)x + i, (int)y + j);
bmp.SetPixel(i, j, MyColor);
}
else
{
bmp.SetPixel(i, j,Color.Gray);
}
}
}
//img2.Save(context.Server.MapPath("~/ClientBin/Img/" + filename));
bmp.Save(context.Server.MapPath("~/ClientBin/TempFile2/" + filename2));
}
catch (Exception ex)
{
ex.ToString();
}
}
public bool IsReusable {
get {
return false;
}
}
private bool Abort()
{
return false;
}
}
3 保存裁剪图片到指定目录
:
<%@ WebHandler Language="C#" Class="Handler_Copy" %>
using System;
using System.Web;
using System.IO;
using System.Media;
public class Handler_Copy : IHttpHandler {
public void ProcessRequest (HttpContext context) {
try
{
File.Copy(context.Server.MapPath("~/ClientBin/TempFile2/")+HttpContext.Current.Request.QueryString["filename"],context.Server.MapPath("~/ClientBin/Img/")+HttpContext.Current.Request.QueryString["filename"]);
}
catch (Exception ex)
{
ex.ToString();
}
}
public bool IsReusable {
get {
return false;
}
}
}