我想动态创建一个镜像,创建的镜像必须满足一些要求。 创建的图像应该是 png,并且它必须具有与从文件加载的 png 相同的行为。 它用于创建在 LWJGL 中使用的纹理。 当我将 png 图像作为文件加载并拥有 BufferedImage 时,我可以对纹理使用以下代码: (纹理构造函数设计用于加载图像)
public class Texture {
public Texture(BufferedImage bi) {
width = bi.getWidth();
height = bi.getHeight();
System.out.println(bi.toString());
int[] pixels_raw = new int[width * height];
pixels_raw = bi.getRGB(0, 0, width, height, null, 0, width);
ByteBuffer pixels = BufferUtils.createByteBuffer(width * height * 4);
for(int i = 0; i < width; i++) {
for(int j = 0; j < height; j++) {
int pixel = pixels_raw[i * width + j]; // This is the error line.
pixels.put((byte)((pixel >> 16) & 0xFF)); // red
pixels.put((byte)((pixel >> 8) & 0xFF)); // green
pixels.put((byte)(pixel & 0xFF)); // blue
pixels.put((byte)((pixel >> 24) & 0xFF)); // alpha
}
}
pixels.flip();
id = glGenTextures();
glBindTexture(GL_TEXTURE_2D, id);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
}
}
但是,当我尝试动态创建图像而不从文件加载任何内容时,我会在上述代码的第 18 行收到 ArrayIndexOutOfBoundsException
(请参阅代码中的注释)。
当然,这与创建的 BufferedImage 的每像素位数有关。我尝试更改 BufferedImage 的图像类型,并在初始化 pixels_raw
数组时更改数组大小。但我仍然遇到数组异常。因此,上述构造函数方法仅在我传递来自加载的 png 的 BufferedImage 实例时才有效。当我传入使用下面的代码动态创建的 BurfferedImage 时,它会给出我之前提到的异常。
public class TextDrawer {
public BufferedImage drawText(String text, Font font, Color color) {
BufferedImage graphicsGetterBi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics g = graphicsGetterBi.getGraphics();
Graphics2D g2 = (Graphics2D) g;
Rectangle2D bounds = font.getStringBounds(text, 0, text.length(), g2.getFontRenderContext());
BufferedImage bi = new BufferedImage((int) bounds.getWidth(), (int) bounds.getHeight(), BufferedImage.TYPE_INT_ARGB);
System.out.println("Created the image. \n");
g2.setColor(color);
g2.setFont(font);
g2.drawString(text, 0, 0);
return bi;
}
}
最佳答案
而不是 int Pixel = Pixels_raw[i * width + j];
应该是 int Pixel = Pixels_raw[i * height + j];
或 int Pixel = Pixels_raw[j * 宽度 + i];
。假设您的图像宽度 = 2x,高度 = x。那么数组大小为2x^2,而你请求的最大索引为(2x - 1) * 2x + x - 1 = 4x^2 - x - 1,对于x > 2 来说大于2x^2
关于Java:从BufferedImage动态创建png图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37910953/