我有一个字节数组,我需要将其转换为图像。我读过这个教程:
http://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/
本教程使用此导入语句中的BufferedImage
andImageIO
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
但是我在任何地方都找不到这些课程。我有安装了 javax 的 JDK x64 版本。有人吗?
我的整个源代码:
public class ReadImageFromFileActivity extends Activity implements OnClickListener {
Context c;
Button read;
ImageView image;
byte[] fileBytes;
byte[] image1;
byte[] image2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
c = getApplicationContext();
read = (Button)findViewById(R.id.file);
read.setOnClickListener(this);
image = (ImageView)findViewById(R.id.image);
image1 = new byte[ 500 * 500];
image2 = new byte[ 500 * 500];
}
public static byte[] getBytesFromFile(Context c) throws IOException {
File file = new File("/mnt/sdcard/LeftIndex.FIR");
Uri URIpath = Uri.fromFile(file);
InputStream is = c.getContentResolver().openInputStream(URIpath);
long length = file.length();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
public void onClick(View v) {
try {
fileBytes = getBytesFromFile(c);
convertByteArray(fileBytes);
} catch (IOException e) {
Log.e("++++getBytesFromFile SAYS: ", "Couldn't read file!!!");
e.printStackTrace();
}
}
public void convertByteArray(byte[] buffer) {
System.arraycopy(buffer, 64, image1, 0, 500 * 500);
System.arraycopy(buffer, 60, image2, 0, 500 * 500);
Bitmap bmp = BitmapFactory.decodeByteArray(image1, 0, image1.length);
ImageView image=new ImageView(this);
image.setImageBitmap(bmp);
}
}
代码说明
在函数中getBytesFromFile
,我从 SD 卡上的 .FIR 文件构建了一个新文件。该文件将被转换为字节数组并返回构造的字节数组。这个字节数组将被传递到一个调用的函数中,该函数convertByteArray
将被分成两个单独的字节数组。我想从这两个字节数组中的每一个构造一个位图。但是logcat只说bitmapFactory返回null。
有人对此有任何解决方案吗?