所以我正在开发一个裁剪图像的组件,它工作正常。
如果图像大于它的父容器(只能是max-width: 100vw
),选择一个的div
要裁剪的图像部分具有将在 BufferedImage.getSubImage(x,y,width,height)
中使用的 x,y,width,height
。
问题:发生这种情况时,x,y,width,height
将相对于渲染后调整大小的图像,但不是真正的图像,因此当传递给 getSubImage
方法时,所选图像的部分将不相同,这会导致图像的不同部分是 裁剪
。
我尝试使用比例方法来计算每个调整大小的图像的像素
,但这会导致太多异常,具体取决于已选择的区域。
有什么想法吗?谢谢。
顺便说一句,真正的代码没有发布,因为它相当长并且正在与 JSF
一起使用,我知道这与问题无关。
代码:
Here's an image showing the component working
当点击 ok 按钮时,一切都归结为:
public String processImage() {
ByteArrayInputStream bais = new ByteArrayInputStream(completeImg);
HttpSession ses = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
ImageContainer curIc = (ImageContainer) ses.getAttribute("ic");
try {
BufferedImage bi = ImageIO.read(bais);
// all values showld be calculated now in relation
// to the real images's dimensions.
x *= bi.getWidth();
y *= bi.getHeight();
width *= bi.getWidth();
height *= bi.getHeight();
BufferedImage bi2 = bi.getSubimage(x, y, width, height);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi2, "jpg", baos);
croppedImg = baos.toByteArray();
curIc.setCroppedImageContent(croppedImg);
} catch (IOException ex) {
FacesContext.getCurrentInstance().addMessage("msgs",
new FacesMessage(FacesMessage.SEVERITY_FATAL, "ioexception", "error processing image"));
}
return null;
}
最佳答案
你提出这个问题是无法解决的:
如果W是真实图像的宽度 和 w 显示的图像 你想计算真实图像的偏移量 X 当您在显示的图像中有 x 偏移时
你可以做 X=(W/w)*x
但是因为缺少w所以无法计算
如果您可以对网页上显示的图像进行屏幕截图,那么您就有了 -
这是我对你所说的理解
--
一道简单的数学题
如果你知道 javascript 中的 w
那么比例因子就是W/w
而不是做
x *= bi.getWidth();
你会
x *= bi.getWidth()/w;
y 依此类推
这个新的 x 是真实图像(在文件上)的 X 裁剪偏移量
试试看它是否给你正确的结果
所以你有
x *= bi.getWidth()/w;
y *= bi.getHeight()/h;
width *= bi.getWidth()/w;
height *= bi.getHeight()/h;
w 和 h 是你从 javascript 得到的
关于javascript - 使用 BufferedImage.getSubImage() 调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34549047/