我已经编写了这段代码来即时裁剪和调整图像的大小。我将经过处理的图像发送到<img src="imagehandler.aspx?img=1.jpg">
之类的浏览器:
imagehandler.aspx:
<%@ Page Language="C#"%>
<%@ import Namespace="System.Drawing" %>
<%@ import Namespace="System.IO" %>
<script runat="server">
System.Drawing.Image oldImage, newImage,cloned,tempImage;
void Page_Load(Object sender, EventArgs e) {
string strFileName = Convert.ToString(Request.QueryString["img"]);
oldImage = System.Drawing.Image.FromFile(Server.MapPath(strFileName));
rect= new Rectangle(0,50,100,100);
cloned = new Bitmap(oldImage ).Clone(rect, tempImage.PixelFormat);
newImage = new Bitmap(cloned);
cloned.Dispose();
Response.ContentType = "image/jpeg";
newImage.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
oldImage.Dispose();
newImage.Dispose();
oldImage = null;
newImage = null;
}
</script>
现在,我想对输出图像添加质量控制,我发现this Q/A该答案提出了一种将图像保存到磁盘的方法。我已尝试使其适合我的目的。目前,我只能将其保存在磁盘上,并且该方法无效。在将结果流式传输到浏览器之前,我不知道如何将输出传递到我自己的代码:
private void VaryQualityLevel(bmp1)
{
ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
System.Drawing.Imaging.Encoder myEncoder= System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
myEncoderParameters.Param[0] = myEncoderParameter;
bmp1.Save(@"c:\TestPhotoQualityFifty.jpg", jgpEncoder,myEncoderParameters);
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
答案 0 :(得分:0)
您可以将位图直接保存到MemoryStream并使用它进行任何操作。您的编码器将应用于此流中的图像。不用传递文件路径作为Save方法的第一个参数,只需传递MemoryStream的实例即可。如果我没记错的话,还有一种方法可以直接将此流作为对浏览器的响应来传递。
using(var ms = new MemoryStream())
{
bmp1.Save(ms, jgpEncoder, myEncoderParameters);
var bmp2 = new BitMap(ms);
//do whatever you want with this image
}
请记住使用语句或为sfream处理方法,以避免内存泄漏。
更多详细信息在这里: https://docs.microsoft.com/en-us/dotnet/api/system.drawing.bitmap?view=netframework-4.7.2