1
有沒有辦法在Google Web Toolkit中進行圖像顏色過濾?類似於使用動作腳本3的彩色矩陣過濾器。以下是動作腳本示例: AS3:How to change a colored Bitmap's BitmapData to black and white?GWT中的顏色過濾
有沒有辦法在Google Web Toolkit中進行圖像顏色過濾?類似於使用動作腳本3的彩色矩陣過濾器。以下是動作腳本示例: AS3:How to change a colored Bitmap's BitmapData to black and white?GWT中的顏色過濾
對於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());
}
不太優雅的動作,但它會做的工作。正如你可以想象的那樣,這將在較大的圖像上消耗大量的處理器時間,如果你需要更好的性能,你可能會考慮gwtgl。
謝謝你的詳細解答。如果圖像尺寸爲48x48,該解決方案工作得非常快,可用於「懸停」或「主動」圖像處理。 – alex