如何按比例调整任何类型的.NET中的形象? [英] How to proportional resize image of any type in .NET?
问题描述
可以在独立的图像类型(BMP,JPG,PNG等)?
Is possible to resize image proportionally in a way independent of the image type (bmp, jpg, png, etc)?
我有这个code,知道少了东西(但不知道是什么):
I have this code and know that something is missing (but don't know what):
public bool ResizeImage(string fileName, string imgFileName,
ImageFormat format, int width, int height)
{
try
{
using (Image img = Image.FromFile(fileName))
{
Image thumbNail = new Bitmap(width, height, img.PixelFormat);
Graphics g = Graphics.FromImage(thumbNail);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle rect = new Rectangle(0, 0, width, height);
g.DrawImage(img, rect);
thumbNail.Save(imgFileName, format);
}
return true;
}
catch (Exception)
{
return false;
}
}
如果不可能,我怎么可以调整比例JPEG图像?
If not possible, how can I resize proportional a jpeg image?
我知道,使用这种方法的,但不知道在哪里把这个(!)
I know that using this method, but don't know where to put this (!).
推荐答案
首先,你不抓住图像的当前高度和宽度。为了调整比例,你需要抓住形象的当前高度/宽度,并基于该调整。
First and foremost, you're not grabbing the CURRENT height and width of the image. In order to resize proportionately you'll need to grab the current height/width of the image and resize based on that.
从那里,找到最大的属性和调整比例的基础上的。
From there, find the greatest attribute and resize proportionately based on that.
例如,假设当前图像为800×600,你想在一个400×400的空间调整比例。抓住比例最大(800),并发现它比新的大小。 800 - > 400 = 0.5立即采取比和由所述第二维(600 * 0.5 = 300)乘
For instance, let's say the current image is 800 x 600 and you wanna resize proportionately within a 400 x 400 space. Grab the greatest proportion (800) and find it's ratio to the new size. 800 -> 400 = .5 Now take that ratio and multiply by the second dimension (600 * .5 = 300).
您新的大小为400×300。 下面是一个PHP的例子(对不起....你会得到它虽然)
Your new size is 400 x 300. Here's a PHP example (sorry....you'll get it though)
$thumb_width = 400;
$thumb_height = 400;
$orig_w=imagesx($src_img);
$orig_h=imagesy($src_img);
if ($orig_w>$orig_h){//find the greater proportion
$ratio=$thumb_width/$orig_w;
$thumb_height=$orig_h*$ratio;
}else{
$ratio=$thumb_height/$orig_h;
$thumb_width=$orig_w*$ratio;
}
这篇关于如何按比例调整任何类型的.NET中的形象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!