javascript - 使用 BufferedImage.getSubImage() 调整图像大小

标签 javascript java jquery html css

所以我正在开发一个裁剪图像的组件,它工作正常。

如果图像大于它的父容器(只能是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/

相关文章:

javascript - 简单的 JavaScript 计时器

javascript - Jquery/Handlebars 错误消息 - Uncaught TypeError : Object [object Object] has no method 'match'

java - 从大量点进行有效搜索

java - 删除[反向退格]按钮

javascript - 单击超链接更改列表元素的颜色

javascript - 如何停止执行 JavaScript 间隔函数?

javascript - AngularJS 如何为 body 背景设置动画(CSS 或 JS)?

javascript - 使用内部/外部 CSS 更改背景图片

java - 获取psx游戏的游戏ID

javascript - 干净地链接 jQuery ajax 请求