[英]How to read a image in java and turn it to byte array?[use Lena.bmp 512x512 as example]
I want to analysis the pixel of lena.bmp (matlab) but I don't know how to do it in java and store it to byte[] 我想分析lena.bmp(matlab)的像素,但是我不知道如何在Java中执行并将其存储到byte []
I have read this aritle: 我已阅读过此文章:
how to convert image to byte array in java? 如何在Java中将图像转换为字节数组?
But when I implement, I find some pixel value that did't exist
. 但是当我实现时,我发现一些不
pixel value that did't exist
。 For example , the pixel range is 0~255, but I can not find '120' on pixel of this photo(lena.bmp). 例如,像素范围是0〜255,但是我在这张照片(lena.bmp)的像素上找不到'120'。
There is my code 有我的密码
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Image_IO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
*
* @author user
*/
public class ReadImage {
public static void main (String []args){
byte[] imageInByte;
int [] kindOfPixel = new int [256];
try{
BufferedImage originalImage = ImageIO.read(new File("C:\\Users\\user\\Desktop\\Project\\LSB_implement\\Lena.bmp"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( originalImage, "bmp", baos );
baos.flush();
imageInByte = baos.toByteArray();
System.out.println(imageInByte.length);
baos.close();
for(int i=0;i<imageInByte.length;i++){
kindOfPixel[imageInByte[i]+128]++; //java byte defined -128~127 (+128)==> 0~256
}
for(int i=0;i<kindOfPixel.length;i++){ //show the pixel color value
System.out.println(i+" , "+kindOfPixel[i]);
}
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}
I compare this information with the histogram of lena.bmp , but it seems have some different... 我将此信息与lena.bmp的直方图进行了比较,但似乎有些不同...
First on java byte 首先在java字节上
You are aware that the signed java byte ranges from -128 to 127. You erred using 128 instead of calculating modulo 256: 您知道带符号的Java字节的范围是-128到127。您使用128而不是计算256模来犯错误:
That simply comes down to: 这简直可以归结为:
kindOfPixel[imageInByte[i] & 0xFF]++;
To look for: 寻找:
Modulo 256 calculation in the other direction goes: 另一个方向上的256模计算是:
byte signed = -126;
int unsigned = signed < 0 ? signed + 256 : signed;
int unsigned = signed & 0xFF; // or simply this
The pixels 像素
A BMP file is not (only) a linearized list of pixels. BMP文件不是(仅)像素线性化列表。 So one better use the int[] BufferedInage.getRGB :
因此,最好使用int [] BufferedInage.getRGB :
int[] pixels = originalImage.getRGB(0, 0, width, height, null, 0, width);
Remains the color representation 保留颜色表示
BMP knows many variants: RGB, indexed etcetera. BMP知道许多变体:RGB,索引等。 Indexed colors need a lookup in the palette.
索引颜色需要在调色板中查找。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.