我一直在尝试使用BufferedImage
数组为每个像素显示图像(int
),但每次我将数组作为参数传递时,结果都是图像损坏。图像没有{ {1}}或alpha
像素。
SpriteSheet类
transparent
展示班级
public class SpriteSheet {
public int width;
public int height;
public int[] pixels;
BufferedImage image;
public SpriteSheet(String path) {
image = null;
try {
image = ImageIO.read(SpriteSheet.class.getResourceAsStream(path));
} catch (IOException ex) {
Logger.getLogger(SpriteSheet.class.getName()).log(Level.SEVERE, null, ex);
}
if (image == null) {
return;
}
this.width = image.getWidth();
this.height = image.getHeight();
pixels = image.getRGB(0, 0, width, height, null, 0, width);
}
}
等级
public class Display {
private GameWindow displayWin;
private BufferedImage displayImage;
public int[] imagePixels;
private BufferStrategy graphBuffer;
private SpriteSheet sheet;
private int width;
private int height;
public Display(int width,int height,GameWindow win,SpriteSheet sheet) {
this.displayImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
this.imagePixels = ((DataBufferInt) this.displayImage.getRaster().getDataBuffer()).getData();
this.sheet=sheet;
this.width=width;
this.height=height;
this.displayWin = win;
this.displayWin.createBufferStrategy(3);
this.graphBuffer= displayWin.getBufferStrategy();
}
public void renderFinal(){
Level test = new Level(this.sheet, 1);
test.render(this);
Graphics g = graphBuffer.getDrawGraphics();
g.drawRect(0, 0, width, height);
g.drawImage(this.displayImage,0, 0,this.displayImage.getWidth(),this.displayImage.getHeight(), null);
g.dispose();
graphBuffer.show();
}
public int getWidth(){
return this.width;
}
public int getHeight(){
return this.height;
}
}
答案 0 :(得分:1)
例如,我想将图像从0切换到230和8到280.这就是你想要做的事情。将图像部分剪切成另一个图像。图像大小不同,因此在转移过程中必须考虑宽度,wcxhc为500x500
我使用以下
public void test() {
String image=".............";
BufferedImage bim=null;
try {
bim=ImageIO.read(new File(image));
}
catch (Exception ex) { System.out.println("error in b "+ex); }
int wc=bim.getWidth(), hc=bim.getHeight();
int[] pix2=bim.getRGB(0, 0, wc, hc, null, 0, wc);
int[] pix=new int[500*500];
for (int y = 8; y <280; y++) {
for (int x=0; x < 230; x++) {
pix[x+y*500]
= pix2[x+y*wc];
}
}
BufferedImage bm=new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
bm.setRGB(0, 0, 500, 500, pix, 0, 500);
}
}
答案 1 :(得分:1)
您必须小心图像编码:颜色或灰度级。
使用BufferedImage,您有两个“好”的解决方案来访问像素。 getRGB()很简单,但速度要慢得多。
1 - 使用光栅更容易,因为它会自动处理编码,但速度较慢。
WritableRaster r = image.getRaster() ;
for (int y=0, nb=0 ; y < image.getHeight() ; y++)
for (int x=0 ; x < image.getWidth() ; x++, nb++)
pixels[nb] = r.getSample(x, y, 0) ; // For a gray level image.
2 - 使用DataBuffer,最快,因为直接访问像素,但你必须处理编码。
switch ( image.getType() )
{
case BufferedImage.TYPE_BYTE_GRAY : // Classical gray level images.
byte[] bb = ((DataBufferByte)image.getRaster().getDataBuffer()).getData() ;
for (int i=0 ; i < bb.length ; i++)
pixels[i] = bb[i] & 0xFF ;
break ;
}