ASP.NET 图像上传与调整大小
Posted
技术标签:
【中文标题】ASP.NET 图像上传与调整大小【英文标题】:ASP.NET Image uploading with Resizing 【发布时间】:2010-09-20 05:52:25 【问题描述】:我有一个 aspx 页面,可以将图片从客户端电脑上传到服务器硬盘
但现在我需要更改我的程序,以便在上传时调整图像大小。
有人对此有任何想法吗?我无法使用输入文件服务器控件找到此类属性/方法
有人指导我吗?
【问题讨论】:
如何从“服务器”“上传”到“客户端”? 我建议使用免费的开源库@Image Resizing In .NET 在一行代码中完成此操作。其他答案(目前)取决于common pitfalls 中的一个或多个。 ImageBuilder.Current.Build(HttpPostedFile f, string destinationFilename, new ResizeSettings("maxwidth=200&maxheight=200")); Here is an example of using jCrop 与ImageResizing.Net libaray。 o_O 我感觉计算机语言学家参与了 .Net 中的图像调整大小 【参考方案1】:文件保存到服务器后,您可以使用这样的代码来调整大小。此代码将在调整大小时处理长/宽比。
public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
System.Drawing.Bitmap bmpOut = null;
try
Bitmap loBMP = new Bitmap(lcFilename);
ImageFormat loFormat = loBMP.RawFormat;
decimal lnRatio;
int lnNewWidth = 0;
int lnNewHeight = 0;
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;
bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
loBMP.Dispose();
catch
return null;
return bmpOut;
【讨论】:
这个问题有点过时,但这对低分辨率图像的处理效果如何?我总是得到格式错误的图像。 我通常通过该代码推送高分辨率图像,所以我无法在那里给你一个好的答案。老实说,连接到应用程序并进行测试非常容易,因此您可能只想尝试一下,我认为这不会花费您大量时间。 除非您在 DrawImage 调用期间在 ImageAttributes 实例中使用 TileModeXY,否则您将在图像的外边框上获得 50% 的白色(或黑色)线。 见***.com/questions/6821261/…【参考方案2】:您将无法“即时”调整大小,因为您需要在执行任何图像转换之前拥有完整的图像。但是,在上传完成之后,在您向用户显示任何结果之前,您可以使用我现在在几个应用中使用过的这种基本的图像大小调整方法:
''' <summary>
''' Resize image with GDI+ so that image is nice and clear with required size.
''' </summary>
''' <param name="SourceImage">Image to resize</param>
''' <param name="NewHeight">New height to resize to.</param>
''' <param name="NewWidth">New width to resize to.</param>
''' <returns>Image object resized to new dimensions.</returns>
''' <remarks></remarks>
Public Shared Function ImageResize(ByVal SourceImage As Image, ByVal NewHeight As Int32, ByVal NewWidth As Int32) As Image
Dim bitmap As System.Drawing.Bitmap = New System.Drawing.Bitmap(NewWidth, NewHeight, SourceImage.PixelFormat)
If bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format1bppIndexed Or _
bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format4bppIndexed Or _
bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format8bppIndexed Or _
bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Undefined Or _
bitmap.PixelFormat = Drawing.Imaging.PixelFormat.DontCare Or _
bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppArgb1555 Or _
bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppGrayScale Then
Throw New NotSupportedException("Pixel format of the image is not supported.")
End If
Dim graphicsImage As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bitmap)
graphicsImage.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality
graphicsImage.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
graphicsImage.DrawImage(SourceImage, 0, 0, bitmap.Width, bitmap.Height)
graphicsImage.Dispose()
Return bitmap
End Function
【讨论】:
+1 指出必须在上传整张图片后调整图片大小。【参考方案3】:另一种方法是允许用户在浏览器中调整大小,然后按照其他答案中的说明调整图像大小。
所以看看这个解决方案,它可以让你upload and crop images with jQuery, jCrop & ASP.NET。
【讨论】:
【参考方案4】:如何调整和上传仅适用于 .jpg 扩展名的图像: 在upload.aspx 页面中
<asp:FileUpload ID="ProductImage" runat="server"/>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload" />
<asp:TextBox runat="server" ID="txtProductName" CssClass="form-control" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtProductName" ErrorMessage="The Product name field is required." />
并上传.aspx.cs 调整大小
/// <summary>
/// Created By Rajib Chowdhury Mob. 01766-306306; Web: http://onlineshoping.somee.com/
/// Complete This Page Coding On January 05, 2014
/// Programing C# By Visual Studio 2013 For Web
/// Dot Net Version 4.5
/// Database Virsion MSSQL Server 2005
/// </summary>
public bool ResizeImageAndUpload(System.IO.FileStream newFile, string folderPathAndFilenameNoExtension, double maxHeight, double maxWidth)
try
// Declare variable for the conversion
float ratio;
// Create variable to hold the image
System.Drawing.Image thisImage = System.Drawing.Image.FromStream(newFile);
// Get height and width of current image
int width = (int)thisImage.Width;
int height = (int)thisImage.Height;
// Ratio and conversion for new size
if (width > maxWidth)
ratio = (float)width / (float)maxWidth;
width = (int)(width / ratio);
height = (int)(height / ratio);
// Ratio and conversion for new size
if (height > maxHeight)
ratio = (float)height / (float)maxHeight;
height = (int)(height / ratio);
width = (int)(width / ratio);
// Create "blank" image for drawing new image
Bitmap outImage = new Bitmap(width, height);
Graphics outGraphics = Graphics.FromImage(outImage);
SolidBrush sb = new SolidBrush(System.Drawing.Color.White);
// Fill "blank" with new sized image
outGraphics.FillRectangle(sb, 0, 0, outImage.Width, outImage.Height);
outGraphics.DrawImage(thisImage, 0, 0, outImage.Width, outImage.Height);
sb.Dispose();
outGraphics.Dispose();
thisImage.Dispose();
// Save new image as jpg
outImage.Save(Server.MapPath(folderPathAndFilenameNoExtension + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
outImage.Dispose();
return true;
catch (Exception)
return false;
还有 Button1_Click 事件
string filePath = "~\\Image\\";//your normal image path
if (Page.IsValid)
HttpPostedFile myFile = ProductImage.PostedFile;//Get Slected Image
int nFileLen = myFile.ContentLength;//Get slected Image Size
string myimag = txtProductName.Text;//Get user input image name
Guid ImageName = Guid.NewGuid();//get unique id
if ((myFile != null) && (nFileLen > 1048576))
LabelAddStatus.Text = "minimum size exceed"; //If file image size 1 MB above
else
try
if (ProductImage.HasFile)
String fileExtension = System.IO.Path.GetExtension(ProductImage.FileName).ToLower();
String[] allowedExtensions = ".jpg" ;//Declare For Allowed Extension
for (int i = 0; i < allowedExtensions.Length; i++)
if (fileExtension == allowedExtensions[i])
// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);
myFile.InputStream.Dispose();
// Save the stream to disk as temporary file. make sure the path is unique!
System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(filePath + "_temp.jpg"),
System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
bool success = ResizeImageAndUpload(newFile, filePath + ("thumbs"+myimag + ImageName), 100, 100);//Save image your thumb image path
success = ResizeImageAndUpload(newFile, filePath + (myimag + ImageName), 768, 1024);//Save image your normal image path
//delete the temp file.
newFile.Close();
System.IO.File.Delete(Server.MapPath(filePath + "_temp.jpg"));
LabelAddStatus.Text = "File uploaded.";
else
LabelAddStatus.Text = "Unable to accept file type..";
catch (Exception)
//No Exception Message
谢谢...
【讨论】:
【参考方案5】:这就是我在项目中所做的,根据您的条件(height/width)您可以更改参数 ie(MaxHeight)
public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
var ratio = (double)maxHeight / image.Height;
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var g = Graphics.FromImage(newImage))
g.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
点击按钮:
protected void Button1_Click(object sender, EventArgs e)
lblmsg.Text="";
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
Guid uid = Guid.NewGuid();
string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
string SaveLocation = Server.MapPath("LogoImagesFolder") + "\\" + uid+fn;
try
string fileExtention = File1.PostedFile.ContentType;
int fileLenght = File1.PostedFile.ContentLength;
if (fileExtention == "image/png" || fileExtention == "image/jpeg" || fileExtention == "image/x-png")
if (fileLenght <= 1048576)
System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(File1.PostedFile.InputStream);
System.Drawing.Image objImage = ScaleImage(bmpPostedImage, 81);
objImage.Save(SaveLocation,ImageFormat.Png);
lblmsg.Text = "The file has been uploaded.";
lblmsg.Style.Add("Color", "Green");
else
lblmsg.Text = "Image size cannot be more then 1 MB.";
lblmsg.Style.Add("Color", "Red");
else
lblmsg.Text = "Invaild Format!";
lblmsg.Style.Add("Color", "Red");
catch (Exception ex)
lblmsg.Text= "Error: " + ex.Message;
lblmsg.Style.Add("Color", "Red");
【讨论】:
【参考方案6】:您需要使用 WebClient 类来下载远程图像。
之后,您可以调整它的大小...使用 DrawImage,而不是 GetThumbnailImage。确保处理掉您的位图和图形句柄..(使用 using)。将所有质量设置设为高。
您可能想先看看source code for my popular image resizer...它将帮助您避免一些常见的麻烦区域。
【讨论】:
【参考方案7】://Here is another WAY fox!!! i have actually modify the code from You all. HIHI
//First, add one textBox and one FileUpload Control, and a button
//paste this in your code behind file... after public partial class admin : System.Web.UI.Page
string OriPath;
string ImageName;
public Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)
Size NewSize;
double tempval;
if (OriginalHeight > FormatSize && OriginalWidth > FormatSize)
if (OriginalHeight > OriginalWidth)
tempval = FormatSize / Convert.ToDouble(OriginalHeight);
else
tempval = FormatSize / Convert.ToDouble(OriginalWidth);
NewSize = new Size(Convert.ToInt32(tempval * OriginalWidth), Convert.ToInt32(tempval * OriginalHeight));
else
NewSize = new Size(OriginalWidth, OriginalHeight); return NewSize;
//Now, On Button click add the folwing code.
if (FileUpload1.PostedFile != null)
ImageName = TextBox1.Text+".jpg";
OriPath = Server.MapPath("pix\\") + ImageName;
//Gets the Full Path using Filecontrol1 which points to actual location in the hardisk :)
using (System.Drawing.Image Img = System.Drawing.Image.FromFile(System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName)))
Size ThumbNailSize = NewImageSize(Img.Height, Img.Width, 800);
using (System.Drawing.Image ImgThnail = new Bitmap(Img, ThumbNailSize.Width, ThumbNailSize.Height))
ImgThnail.Save(OriPath, Img.RawFormat);
ImgThnail.Dispose();
Img.Dispose();
//Enjoy. If any problem,, mail me at izacmail@gmail.com
【讨论】:
【参考方案8】:要缩小图像并缩小尺寸,只需进行以下更改
bmpOut = new Bitmap(lnNewWidth, lnNewHeight, **System.Drawing.Imaging.PixelFormat.Format24bppRgb**);
Graphics g = Graphics.FromImage(bmpOut);
如上所述,将 imagem 设置为 Format24bppRgb PixelFormat。
当你保存文件时,你也设置了 ImageFormat。像这样:
bmpOut.Save(PathImage, System.Drawing.Imaging.ImageFormat.Jpeg);
【讨论】:
【参考方案9】:您可以使用它,它对我来说非常有用。但它对我来说不能很好地处理低分辨率图像。谢天谢地,我已经习惯了其中的许多人。只需将图像byte[]
和预期输出发送给它,您就可以开始了。
public static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
Size newSize = CalculateDimensions(oldImage.Size, targetSize);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb))
newImage.SetResolution(oldImage.HorizontalResolution, oldImage.VerticalResolution);
using (Graphics canvas = Graphics.FromImage(newImage))
canvas.SmoothingMode = SmoothingMode.AntiAlias;
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
MemoryStream m = new MemoryStream();
newImage.Save(m, ImageFormat.Jpeg);
return m.GetBuffer();
private static Size CalculateDimensions(Size oldSize, int targetSize)
Size newSize = new Size();
if (oldSize.Width > oldSize.Height)
newSize.Width = targetSize;
newSize.Height = (int)(oldSize.Height * (float)targetSize / (float)oldSize.Width);
else
newSize.Width = (int)(oldSize.Width * (float)targetSize / (float)oldSize.Height);
newSize.Height = targetSize;
return newSize;
【讨论】:
【参考方案10】:您可以在发送到服务器之前使用 ActiveX 控件调整大小。这里有一个免费的 ASP.net 图片上传组件(我相信这与 Facebook 实际使用的相同):
http://forums.aurigma.com/yaf_postst2145_Image-Uploader-ASPNET-Control.aspx
让我知道它是否有效,我正在考虑在我的工作项目中实施它。
编辑:看起来对象的包装器是免费的,但实际组件本身将花费您大约 200 美元。我确认它与 Facebook 使用的组件相同。
【讨论】:
【参考方案11】:using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
public partial class admin_AddPhoto : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
string reportPath = Server.MapPath("../picnic");
if (!Directory.Exists(reportPath))
Directory.CreateDirectory(Server.MapPath("../picnic"));
protected void PhotoForm_ItemInserting(object sender, FormViewInsertEventArgs e)
FormView uploadForm = sender as FormView;
FileUpload uploadedFile = uploadForm.FindControl("uploadedFile") as FileUpload;
if (uploadedFile != null)
string fileName = uploadedFile.PostedFile.FileName;
string pathFile = System.IO.Path.GetFileName(fileName);
try
uploadedFile.SaveAs(Server.MapPath("../picnic/") + pathFile);
catch (Exception exp)
//catch exception here
try
Bitmap uploadedimage = new Bitmap(uploadedFile.PostedFile.InputStream);
e.Values["ImageWidth"] = uploadedimage.Width.ToString();
e.Values["ImageHeight"] = uploadedimage.Height.ToString();
// Make output File Name
char[] splitter = '.' ;
string[] splitFile = pathFile.Split(splitter);
string OutputFilename = splitFile[0] + "s";
System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
System.Drawing.Image thumbImage = uploadedimage.GetThumbnailImage(74, 54, myCallback, IntPtr.Zero);
thumbImage.Save(Server.MapPath("../picnic/") + OutputFilename + ".jpg");
e.Values["Thumbnail"] = "./picnic/" + OutputFilename + ".jpg";
catch (Exception ex)
//catch exception here
e.Values["Pic"] = "./picnic/" + pathFile;
e.Values["Url"] = "./picnic/" + pathFile;
e.Values["dateEntered"] = DateTime.Now.ToString();
public bool ThumbnailCallback()
return false;
这使用 FileUpload 和 FormView 来插入。然后我使用 System.Drawing.Imaging 中提供的GetThumnailImage() 方法。您可以输入任何宽度和高度值,它会相应地收缩/拉伸。
uploadedimage.GetThumbnailImage(W, H, myCallback, IntPtr.Zero);
希望这会有所帮助。
【讨论】:
【参考方案12】:图像文件的上传由 ASP.NET 4.0 客户端回调执行。如果您不熟悉客户端回调,那么我建议您查看 ASP.Net AJAX Control Toolkit AsyncFileUpload Control without page refresh or PostBack in ASP.Net Web Page 或 ASP.Net AJAX Update Panel。用户使用文件字段控件选择文件后立即触发回调。
【讨论】:
【参考方案13】:public string ResizeImageAndSave(int Width, int Height, string imageUrl, string destPath)
System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(imageUrl);
double widthRatio = (double)fullSizeImg.Width / (double)Width;
double heightRatio = (double)fullSizeImg.Height / (double)Height;
double ratio = Math.Max(widthRatio, heightRatio);
int newWidth = (int)(fullSizeImg.Width / ratio);
int newHeight = (int)(fullSizeImg.Height / ratio);
//System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
System.Drawing.Image thumbNailImg = fullSizeImg.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
//DateTime MyDate = DateTime.Now;
//String MyString = MyDate.ToString("ddMMyyhhmmss") + imageUrl.Substring(imageUrl.LastIndexOf("."));
thumbNailImg.Save(destPath, ImageFormat.Jpeg);
thumbNailImg.Dispose();
return "";
public bool ThumbnailCallback() return false;
【讨论】:
欢迎来到 *** 并感谢您抽出宝贵的时间来回答。考虑添加一些解释。【参考方案14】:private void ResizeImage(FileUpload fileUpload)
// First we check to see if the user has selected a file
if (fileUpload.HasFile)
// Find the fileUpload control
string filename = fileUpload.FileName;
// Check if the directory we want the image uploaded to actually exists or not
if (!Directory.Exists(MapPath(@"Uploaded-Files")))
// If it doesn't then we just create it before going any further
Directory.CreateDirectory(MapPath(@"Uploaded-Files"));
// Specify the upload directory
string directory = Server.MapPath(@"Uploaded-Files\");
// Create a bitmap of the content of the fileUpload control in memory
Bitmap originalBMP = new Bitmap(fileUpload.FileContent);
// Calculate the new image dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
int sngRatio = origWidth / origHeight;
int newWidth = 100;
int newHeight = newWidth / sngRatio;
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
// Save the new graphic file to the server
newBMP.Save(directory + "tn_" + filename);
// Once finished with the bitmap objects, we deallocate them.
originalBMP.Dispose();
newBMP.Dispose();
oGraphics.Dispose();
// Write a message to inform the user all is OK
label.Text = "File Name: <b style='color: red;'>" + filename + "</b><br>";
label.Text += "Content Type: <b style='color: red;'>" + fileUpload.PostedFile.ContentType + "</b><br>";
label.Text += "File Size: <b style='color: red;'>" + fileUpload.PostedFile.ContentLength.ToString() + "</b>";
// Display the image to the user
Image1.Visible = true;
Image1.ImageUrl = @"Uploaded-Files/tn_" + filename;
else
label.Text = "No file uploaded!";
【讨论】:
与其他答案相比,附加值是多少?以上是关于ASP.NET 图像上传与调整大小的主要内容,如果未能解决你的问题,请参考以下文章