我尝试将接收的字节[]显示为位图。
InputStream stream = mySocket.getInputStream();
byte[] datas = new byte[SIZE?];
Bitmap bmp = BitmapFactory.decodeByteArray(datas, 0, datas.length);
ImageView view = new ImageView(MyServer.this);
view.setImageBitmap(bmp);
lChat.addView(view);
我不知道字节数应该有多大,我不知道如何在byte []中获取inputStream的数据。任何人都可以帮助我吗?
答案 0 :(得分:0)
创建ByteArrayOutputStream
- 它是一个输出流,其中数据被写入字节数组。然后使用copy()
方法(取自Commons IO)将输入流复制到输出流:
InputStream stream = mySocket.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(stream, output);
byte[] data = output.toByteArray();
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
...
data
数组的长度与从输入流读取的数据的长度相同。
请查看以下copy()
方法:
public static int copy(InputStream input, OutputStream output) throws IOException {
int n, count = 0;
byte[] buffer = new byte[4 * 1024];
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
答案 1 :(得分:0)
使用inputStreamToByteArray
方法将InputStream
解析为byte[]
:
public byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
return baos.toByteArray();
}
同时在加载大型位图时,请考虑Google的建议。根据您的需要调整它们的大小。通过这样做,您可以防止许多内存故障:
private Bitmap getBitmap(InputStream is, int requestedMaxWidth, int requestedMaxHeight) throws IOException {
// parse inputStream to byte[]
byte[] dataToBeDecode = inputStreamToByteArray(is);
BitmapFactory.Options options = new BitmapFactory.Options();
// First see the width and height of incoming bitmap
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(dataToBeDecode, 0, dataToBeDecode.length, options);
// Calculate inSampleSize for resizing
options.inSampleSize = calculateInSampleSize(options, requestedMaxWidth, requestedMaxHeight);
// Now resize and get the bitmap
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeByteArray(dataToBeDecode, 0, dataToBeDecode.length, options);
return bitmap;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2
// and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
修改:阅读Google加载的大型位图文档。 See link