由於您imageByte的來源是未知的,它是很難說什麼地方出了錯。但是,如果你正在創建byteSource,則可能是下面的代碼會幫助你,因爲從Javadoc文檔ImageIO.read()
返回一個BufferedImage,作爲使用 一個ImageReader解碼所提供File的結果從當前登記的 中自動選擇。該文件包裝在ImageInputStream中。如果沒有 註冊的ImageReader聲稱能夠讀取結果 流,則返回null。
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
/**
* Created by ankur on 13/7/15.
* The Following program will read an image file.
* convert it into byte array, and then reuse the
* converted byte array, and convert it back to new BufferedImage
*
*/
public class ImageToBuf {
public static void main(String... strings) throws IOException {
byte[] imageInByte;
//read the image
BufferedImage originalImage = ImageIO.read(new File("/home/ankur/Pictures/BlpRb.png"));
//convert BufferedImage to byte array
ByteArrayOutputStream byteOutS = new ByteArrayOutputStream();
ImageIO.write(originalImage, "png", byteOutS);
byteOutS.flush();
imageInByte = byteOutS.toByteArray();
byteOutS.close();
//convert byte array back to BufferedImage
InputStream readedImage = new ByteArrayInputStream(imageInByte);
BufferedImage bfImage = ImageIO.read(readedImage);
System.out.println(bfImage);
}
}
輸出(在我amchine):
[email protected]: type = 13 IndexColorModel: #pixelBits = 8 numComponents = 3 color space = [email protected] transparency = 1 transIndex = -1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 4959 height = 3505 #numDataElements 1 dataOff[0] = 0
的Javadoc說:*如果沒有註冊的ImageReader聲稱能夠讀取得到的流,則返回null *所以,你的字節。數組不包含Java可以解碼的圖像。這些字節從哪裏來? –