裁剪图像有时是一个错误的地方 [英] Cropping images sometimes a wrong area
问题描述
我使用 jQuery-cropbox 在Web应用程序中裁剪图像。
大多数情况下,一切都运行平稳,但时不时地,生成的图像是错误的,就好像裁剪应用了错误的坐标一样。
举个例子,考虑这个 image :
在裁剪框中,我缩放并拖动,直到得到这个:
但是当我点击修剪按钮时,它给了我这个:
这里是裁剪代码:
private Bitmap CropImage(Image img,Rectangle rect)
{
位图newImg =新位图(rect.Width,rect.Height);
图形g = Graphics.FromImage(newImg);
g.DrawImage(img,-rect.X,-rect.Y);
返回newImg;
// ...
//保存图片
var streamOut = new MemoryStream();
位图newImg = CropImage(oldImg,rect);
newImg.Save(streamOut,ImageFormat.Png);
oldImg
是之前发布的图片, rect
我用来裁剪的坐标。
我检查了矩形的坐标当然是正确的。 p>
作为参考,为了获得提供坐标的结果(这些可能并不完全准确,我从第二次测试中拿走了它们,所以我确实将图片置于不同的位置) :
x:47
y:94
w:150
h:150
发生了什么事?
您的图片(已发布)有72dpi;您的屏幕,因此您使用的图形可能有96dpi。
这将导致您看到的效果。
为了避免这种效应,只需在绘制到Graphics对象的分辨率之前设置 img
的分辨率即可:
img.SetResolution((int)g.DpiX,(int)g.DpiY);
I'm using jQuery-cropbox to crop images on a web application.
Everything is running smoothly most of the time, but from time to time, the generated image is wrong, as if the cropping was applied with wrong coordinates.
As an example, consider this image :
In cropbox, I zoom and drag until I get this :
But when I click on the crop button, it gives me this:
Here is the cropping code:
private Bitmap CropImage(Image img, Rectangle rect)
{
Bitmap newImg = new Bitmap(rect.Width, rect.Height);
Graphics g = Graphics.FromImage(newImg);
g.DrawImage(img, -rect.X, -rect.Y);
return newImg;
}
//...
// save image
var streamOut = new MemoryStream();
Bitmap newImg = CropImage(oldImg, rect);
newImg.Save(streamOut, ImageFormat.Png);
oldImg
is the image previously posted, rect
the coordinates I use to crop.
I checked the coordinates in rect of course, they are correct.
For reference, to obtain the result provided the coordinates are (those may not be exactly accurate, I took them from a second test, so I certainly placed the picture a bit differently):
x: 47
y: 94
w: 150
h: 150
What is happening ?
Your image (as posted) has 72dpi; your screen and therefore the Graphics you use probably have 96dpi.
This will lead to the effect you see.
To avoid the effect simply set the resolution of img
before drawing it to the one in your Graphics object:
img.SetResolution((int)g.DpiX, (int)g.DpiY);
这篇关于裁剪图像有时是一个错误的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!