asp.net - 无需下载即可在服务器上调整图像大小
问题描述
我在 asp.net 的服务器上有图像。我想通过复制、调整大小、重命名并最后将它们保存在服务器本身来创建他们的缩略图。对于压缩,我有代码,但如何保存文件。
if (fileUploader.HasFile)
{
string fileName = Path.GetFileName(fileUploader.PostedFile.FileName);
string ext = string.Empty;
ext = System.IO.Path.GetExtension(fileUploader.FileName.ToString()).ToLower();
fileUploader.PostedFile.SaveAs(Server.MapPath("~/Images_Coach/" + hdnCoachId.Value + "/") + hdnCoachId.Value + ext);
int width = Convert.ToInt32(150);
int height = Convert.ToInt32(150);
Stream inp_Stream = fileUploader.PostedFile.InputStream;
using (var image = System.Drawing.Image.FromStream(inp_Stream))
{
Bitmap myImg = new Bitmap(width, height);
Graphics myImgGraph = Graphics.FromImage(myImg);
myImgGraph.CompositingQuality = CompositingQuality.HighQuality;
myImgGraph.SmoothingMode = SmoothingMode.HighQuality;
myImgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imgRectangle = new Rectangle(0, 0, width, height);
myImgGraph.DrawImage(image, imgRectangle);
newFile = hdnCoachId.Value + "_icon" + ext;
// Save the file
var path = Path.Combine(Server.MapPath("~/Images_Coach/" + hdnCoachId.Value + "/"), newFile);
myImg.Save(path, image.RawFormat);
}
}
解决方案
我可以将文件转换为字节数组,然后将其转换为流
foreach (var fileName in Directory.GetFiles(dirFile))
{
if (fileName.Contains(dir))
{
string newFile = string.Empty;
//Read the File into a Byte Array.
string ext = string.Empty;
ext = System.IO.Path.GetExtension(fileName.ToString()).ToLower();
byte[] bytes = File.ReadAllBytes(fileName);
Stream inp_Stream = new MemoryStream(bytes);
int width = Convert.ToInt32(150);
int height = Convert.ToInt32(150);
using (var image = System.Drawing.Image.FromStream(inp_Stream))
{
Bitmap myImg = new Bitmap(width, height);
Graphics myImgGraph = Graphics.FromImage(myImg);
myImgGraph.CompositingQuality = CompositingQuality.HighQuality;
myImgGraph.SmoothingMode = SmoothingMode.HighQuality;
myImgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imgRectangle = new Rectangle(0, 0, width, height);
myImgGraph.DrawImage(image, imgRectangle);
newFile = dir + "_icon" + ext;
// Save the file
var newPath = Path.Combine(Server.MapPath("~/Images_Coach/" + dir + "/"), newFile);
myImg.Save(newPath, image.RawFormat);
}
}
//File.Delete
// fileName is the file name
}
推荐阅读
- java - 使用 Intellij IDEA 运行 Spring Boot 应用程序时出现 gradle 问题
- python - Tensorflow model.fit 没有启动
- python - 使用 Python 连接到 PSQL 数据库
- c# - C#中的字符串引用
- c# - 文件上传在本地工作,但不在服务器上
- cisco - 使用 trex 测试 vpp 性能,memif 无法连接
- python - 在 Python 中跳过数据类型错误的行
- javascript - 使用 Javascript 禁用特定复选框
- python - 有什么办法可以将图片添加到我的 QTextEdit 中吗?
- webserver - 为 Windows 选择 Web 服务器以运行 Angular 应用程序