我有一个允许用户上传图片的页面。问题是我的旧用户无法自己调整图像大小。我想允许他们上传任意大小的图片,然后当服务器获得它时,它会创建这张图片的小副本。
答案 0 :(得分:14)
有很多方法可以调整图像大小,但我喜欢这个
System.Drawing.Image image = System.Drawing.Image.FromFile("FilePath");
int newwidthimg = 160;
float AspectRatio = (float)image.Size.Width / (float)image.Size.Height;
int newHeight = Convert.ToInt32(newwidthimg / AspectRatio);
Bitmap thumbnailBitmap = new Bitmap(newwidthimg, newHeight);
Graphics thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newwidthimg, newHeight);
thumbnailGraph.DrawImage(image, imageRectangle);
thumbnailBitmap.Save("FilePath", ImageFormat.Jpeg);
thumbnailGraph.Dispose();
thumbnailBitmap.Dispose();
image.Dispose();
我已修复宽度,因为我希望所有图像的宽度为160,高度根据宽高比
答案 1 :(得分:8)
您可以使用某种 resizeMethod 。
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile pf = FileUpload1.PostedFile;
System.Drawing.Image bm = System.Drawing.Image.FromStream(pf.InputStream);
bm = ResizeBitmap((Bitmap) bm, 100, 100); /// new width, height
bm.Save(Path.Combine(YOURUPLOADPATH, pf.FileName);
}
private Bitmap ResizeBitmap(Bitmap b, int nWidth, int nHeight)
{
Bitmap result = new Bitmap(nWidth, nHeight);
using (Graphics g = Graphics.FromImage((System.Drawing.Image)result))
g.DrawImage(b, 0, 0, nWidth, nHeight);
return result;
}
另一方面,上传例如 3 MB文件,然后 * 调整大小 * 20kb pic - 不声音非常好给我。也许您可以考虑限制上传文件大小。
答案 2 :(得分:1)
这是最近的解决方案。希望它有所帮助
http://forums.asp.net/t/1657138.aspx/1?C+Resize+Profile+Image
protected void UploadButton_Click(object sender, EventArgs e)
{
if (File1.HasFile)
{
string fileName = Server.HtmlEncode(File1.FileName);
string extension = System.IO.Path.GetExtension(fileName);
System.Drawing.Image image_file = System.Drawing.Image.FromStream(File1.PostedFile.InputStream);
int image_height = image_file.Height;
int image_width = image_file.Width;
int max_height = 100;
int max_width = 100;
image_height = (image_height * max_width) / image_width;
image_width = max_width;
if (image_height > max_height)
{
image_width = (image_width * max_height) / image_height;
image_height = max_height;
}
Bitmap bitmap_file = new Bitmap(image_file, image_width, image_height);
System.IO.MemoryStream stream = new System.IO.MemoryStream();
bitmap_file.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Position = 0;
byte[] data = new byte[stream.Length + 1];
stream.Read(data, 0, data.Length);
Profile.Picture = data;
Profile.PictureType = "image/png";
}
}