上传图像后不减小asp.net中的大小...?
问题描述:
我的要求是上传图片并添加到水印图片,其工作正常,但主图像大小为1mb后添加水印相同的图像大小是400kb .size减少但我的要求大小正在增加我正在写这个代码.....在drawimage方法大小减少后请给我一个解决方案....
my requirement is upload the image and add to watermark image its working fine but the main image size is 1mb after added the watermark in same image size is 400kb .size is reducing but my requirement size is increasing i am writing this code.....after drawimage method size is reducing please give me a solution....
protected void Button1_Click(object sender, EventArgs e)
{
FileName = Guid.NewGuid().ToString();
FilePath = @"C:\Users\bravemountravi\Desktop\Image\Attachments\" + FileName + "." + "jpg";
System.Drawing.Image Mainimg = System.Drawing.Image.FromFile(@"C:\Users\travi\Desktop\Image\Attachments\funny-dog-wallpaper-and-picture-p0d-funny-dog-photo-hd-ahhw.jpg");
System.Drawing.Image img2 = System.Drawing.Image.FromFile(@"C:\Users\travi\Desktop\Image\Images\watermark3.png");
Graphics g = Graphics.FromImage(Mainimg);
double _scalefactor = (Mainimg.Width / 4800.0);
if (_scalefactor <= 0.1)
{
_scalefactor = 0.1;
}
else if (_scalefactor <= 0.2)
{
_scalefactor = 0.2;
}
else if (_scalefactor >= 1)
{
_scalefactor = 1.0;
}
double _newwidth = (_scalefactor * img2.Width);
//double _newHeight = ((_newwidth / img2.Width) * (img2.Height));
double _newHeight = (_scalefactor * img2.Height);
Bitmap bitimg = WaterMarkScaleImage(img2, Convert.ToInt32(Math.Round(_newwidth, 0)), Convert.ToInt32(Math.Round(_newHeight, 0)));
System.Drawing.Image scaleimg = (System.Drawing.Image)bitimg;
int left = Mainimg.Width - scaleimg.Width;
int top = Mainimg.Height - scaleimg.Height;
g.DrawImage(scaleimg, left, top, scaleimg.Width, scaleimg.Height);
g.Dispose();
Mainimg.Save(FilePath);
}
public Bitmap WaterMarkScaleImage(System.Drawing.Image image, int maxWidth, int maxHeight)
{
var newImage = new Bitmap(maxWidth, maxHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, maxWidth, maxHeight);
Bitmap bmp = new Bitmap(image);
return bmp;
}
答
当你加载然后保存一个jpg文件(即使你什么也不做你可能会得到一个较小的文件 - 和一个更糟糕的图像。这是jpg文件如何工作的基础:它们是一种有损压缩方法,当它们具有相似的颜色时,通过组合它们来减少像素数。
试一试:阅读jpg,保存并重复10次。将原始文件与最终文件进行比较。
因此,如果您上传文件,进行编辑并保存,则很可能会获得质量较低的较小文件。
您可以尝试将其保存为位图文件或无损压缩格式 - 但这些也可能非常大,并且与原始版本的大小不同,除非位图几乎是一个固定大小基于分辨率。
When you load and then save a jpg file (even of you do nothing to it) you ate likely to get a smaller file - and a worse image. This is fundamental to how jpg files work: they are a lossy compression method, which reduces the number of pixels by combining them when they have a similar colour.
Try it: read a jpg, save it and repeat 10 times. Compare the original to the final file.
So if you upload a file, edit it, and save it you are very likely to get a smaller file with lower quality.
You could try saving it as a bitmap file or a lossless compression format - but those can also be quite large, and won't be the same size as the original except for bitmaps which are pretty much a fixed size based on the resolution.