我使用 clientcanvas 来编辑我用 tabris 创建的应用程序中的图片。到目前为止它工作得很好,但是我遇到了将编辑后的图片保存为新图像的问题。有没有人有这方面的经验?
问问题
218 次
1 回答
0
您需要将 swt ImageData 转换为 awt BufferedImage 并保存。用于此的实用程序可能如下所示:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.WritableRaster;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.RGB;
public class ImageUtil {
public static BufferedImage convertToAWT( ImageData data ) {
BufferedImage imageToDraw = bgToAWT( data, data.width, data.height );
BufferedImage result = new BufferedImage( data.width, data.height, BufferedImage.TYPE_INT_RGB );
drawWhiteBackground( result );
Graphics graphics = result.getGraphics();
graphics.drawImage( imageToDraw, 0, 0, null );
graphics.dispose();
return result;
}
/*
* See
* http://m4tx.pl/en/2013/01/01/java-swt-to-awt-and-vice-versa-image-conversion
* -with-transparency-support/
*/
public static BufferedImage bgToAWT( ImageData data, int width, int height ) {
BufferedImage result = null;
ColorModel colorModel = null;
PaletteData palette = data.palette;
if( palette.isDirect ) {
BufferedImage bufferedImage = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
for( int y = 0; y < data.height; y++ ) {
for( int x = 0; x < data.width; x++ ) {
int pixel = data.getPixel( x, y );
RGB rgb = palette.getRGB( pixel );
bufferedImage.setRGB( x, y, data.getAlpha( x, y ) << 24
| rgb.red << 16
| rgb.green << 8
| rgb.blue );
}
}
result = bufferedImage;
} else {
RGB[] rgbs = palette.getRGBs();
byte[] red = new byte[ rgbs.length ];
byte[] green = new byte[ rgbs.length ];
byte[] blue = new byte[ rgbs.length ];
for( int i = 0; i < rgbs.length; i++ ) {
RGB rgb = rgbs[ i ];
red[ i ] = ( byte )rgb.red;
green[ i ] = ( byte )rgb.green;
blue[ i ] = ( byte )rgb.blue;
}
if( data.transparentPixel != -1 ) {
colorModel = new IndexColorModel( data.depth,
rgbs.length,
red,
green,
blue,
data.transparentPixel );
} else {
colorModel = new IndexColorModel( data.depth, rgbs.length, red, green, blue );
}
BufferedImage bufferedImage = new BufferedImage( colorModel,
colorModel.createCompatibleWritableRaster( width,
height ),
false,
null );
WritableRaster raster = bufferedImage.getRaster();
int[] pixelArray = new int[ 1 ];
for( int y = 0; y < data.height; y++ ) {
for( int x = 0; x < data.width; x++ ) {
int pixel = data.getPixel( x, y );
pixelArray[ 0 ] = pixel;
raster.setPixel( x, y, pixelArray );
}
}
result = bufferedImage;
}
return result;
}
private static void drawWhiteBackground( BufferedImage bufferedImage ) {
Graphics2D graphics = bufferedImage.createGraphics();
graphics.setColor( new Color( 255, 255, 255 ) );
graphics.fillRect( 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight() );
}
}
于 2015-06-16T13:25:02.583 回答