有一个非常简单的.jpg图像,我想将其转换为矩阵。但是使用getRGB(i,j)指向像素会给ArrayIndexOutOfBounds提供运行时异常。以下代码的图像大小是否有任何限制? 它只是显示它在整个图像中获得的第一个颜色代码。
// This will be the testing variable, where in the actual script
// we'll check the response code of file_get_contents
$count = 0;
function funcTwo( &$count ) {
// Here I'd run file_get_contents and parse the headers
$count = ++$count;
echo "functTwo() running $count... \n";
// Here I'll test for response code 429, if true, restart
if ($count !== 5) {
echo "Count only = $count so we're gonna take a nap... \n";
sleep(1);
echo "Waking from sleep $count and rerunning myself... \n";
funcTwo($count);
return;
}
echo "Count finally = $count, exiting funcTwo... \n";
}
// This function does the main work that relies on the successful response from
function funcOne( $count ) {
echo "functOne() running! \n";
// The function will be delayed here until a successful response is returned
funcTwo($count);
echo "Count finally = $count, so now we can finally do the work that \n";
echo "depends on a successful response from funcTwo() \n";
// Do main work
echo "Work done, exiting funcOne and script... \n";
}
funcOne($count);
然后我应用了嵌套的for循环并使用了
BufferedImage img=ImageIO.read(new File("stars.jpg"));
int pix[][]= new int[img.getHeight()][img.getWidth()];
答案 0 :(得分:1)
这个功能正是你提到的,它对我来说很好。我相信你可能在你的嵌套for循环中做错了。
public int[][] getMatrixOfImage(BufferedImage bufferedImage) {
int width = bufferedImage.getWidth(null);
int height = bufferedImage.getHeight(null);
int[][] pixels = new int[width][height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
pixels[i][j] = bufferedImage.getRGB(i, j);
}
}
return pixels;
}
答案 1 :(得分:0)
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageUtil {
public static Color[][] loadPixelsFromFile(File file) throws IOException {
BufferedImage image = ImageIO.read(file);
Color[][] colors = new Color[image.getWidth()][image.getHeight()];
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
colors[x][y] = new Color(image.getRGB(x, y));
}
}
return colors;
}
public static void main(String[] args) throws IOException {
Color[][] colors = loadPixelsFromFile(new File("stars.jpg"));
System.out.println("Color[0][0] = " + colors[0][0]);
}
}
答案 2 :(得分:0)
您可能交换了宽度和高度。
尝试替换
int pix[][]= new int[img.getHeight()][img.getWidth()];
与
int pix[][]= new int[img.getWidth()][img.getHeight()]; // <--- width first