【问题标题】:color filtering in GWTGWT 中的颜色过滤
【发布时间】:2012-06-16 07:10:55
【问题描述】:

有没有办法在 Google Web Toolkit 中进行图像颜色过滤?使用动作脚本 3 的颜色矩阵过滤器之类的东西。这是动作脚本示例: AS3:How to change a colored Bitmap's BitmapData to black and white?

【问题讨论】:

    标签: gwt colormatrixfilter


    【解决方案1】:

    对于 HTML(以及 GWT)中的图像操作,您需要使用 canvas 元素。据我所知,画布没有为您提供任何应用过滤器的快捷方式,您需要手动进入并修改像素。让我们以黑白为例。在调用此方法之前,您需要确保图像已经加载:

    public void toBlackAndWhite(Image image)
    {
        // Create an off-screen canvas element to do the work.
        Canvas canvas = Canvas.createIfSupported();
    
        // Do nothing if canvas is not supported.
        if (canvas == null)
            return;
    
        // Size the canvas to fit the image.
        canvas.setCoordinateSpaceHeight(image.getHeight());
        canvas.setCoordinateSpaceWidth(image.getWidth());
    
        // Pull the image's underlying DOM element
        ImageElement img = ImageElement.as(image.getElement());
    
        // The 2D context does all the drawing work on the canvas
        Context2d context = canvas.getContext2d();
    
        context.drawImage(img, 0, 0); // Now the canvas contains the image.
    
        // ImageData represents the canvas rgba data as an array of bytes.
        ImageData imageData = context.getImageData(0, 0,
                                  image.getWidth(), image.getHeight());
    
        // Now the real work:
        for (int x = 0; x < imageData.getWidth(); ++x) {
            for (int y = 0; y < imageData.getHeight(); ++y) {
                 // RGB values are 0-255
                 int average = (imageData.getRedAt(x,y) +
                                imageData.getGreenAt(x,y) +
                                imageData.getBlueAt(x,y)) / 3;
    
                 imageData.setRedAt(average, x,y);
                 imageData.setGreenAt(average, x,y);
                 imageData.setBlueAt(average, x,y);
             }
        }
    
        // ImageData is a copy of the data on the canvas, so
        // we need to write it back.
        context.putImageData(imageData,0,0);
    
        // Now the canvas contains a black and white version
        // of the image. Canvas is a Widget so you could attach
        // it to the page directly if you want. Here we're going
        // to replace the contents of the original image element
        // with a url-encoded version of the canvas contents.
        image.setUrl(canvas.toDataUrl());
    }
    

    不像actionscript那么优雅,但它可以完成这项工作。您可以想象,这会在较大的图像上消耗大量的处理器时间,如果您需要更好的性能,您可以考虑gwtgl

    【讨论】:

    • 感谢您的详细解答。在图像大小为 48x48 的情况下,此解决方案运行速度非常快,可用于“悬停”或“活动”图像操作。