从Android中的httpResponse获取图像内容
作者:互联网
我试图从http响应中获取图像,但无法将流转换为位图.
请让我知道,我在这里失踪了什么.
仅供参考 – 图像内容以原始二进制形式接收.它是一个jpeg图像.
程序如下:
>制作HttpRequest.
>作为响应检查200 – >获取httpentity内容.
>使用BitMap工厂将流转换为位图.
>将位图设置为imageview
在postExecute的AsyncTask中执行此操作
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(endpoint);
// Adding Headers ..
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
if (response.getStatusLine().getStatusCode() == 200) {
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
return instream;
// instream.close();
}
}
}
在postExecute的AsyncTask中执行此操作
if (null != instream) {
Bitmap bm = BitmapFactory.decodeStream(instream);
if(null == bm){
Toast toast = Toast.makeText(getApplicationContext(),
"Bitmap is NULL", Toast.LENGTH_SHORT);
toast.show();
}
ImageView view = (ImageView) findViewById(R.id.picture_frame);
view.setImageBitmap(bm);
}
提前致谢.
解决方法:
终于找到了答案.下面是片段 – 可能有助于使用http响应的新手.
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(endpoint);
// Adding Headers ..
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
if (response.getStatusLine().getStatusCode() == 200) {
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String path = "/storage/emulated/0/YOURAPPFOLDER/FILENAME.EXTENSION";
FileOutputStream output = new FileOutputStream(path);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = instream.read(buffer)) != -1) {
output.write(buffer, 0, len);
}
output.close();
}
我们可以将内容保存在bytearray中并从中获取位图,而不是将文件保存到磁盘.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
try {
// instream is content got from httpentity.getContent()
while ((len = instream.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
byte[] b = baos.toByteArray();
Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
ImageView imageView = (ImageView)findViewById(R.id.picture_frame);
imageView.setImageBitmap(bmp);
仅供参考 – 在android fileoutput流中,写入本地磁盘必须在非UI线程中完成(在我的情况下使用了异步任务,并且此处未添加该部分).
谢谢 ..
标签:android,inputstream,bitmap,httpresponse,httpentity 来源: https://codeday.me/bug/20190825/1716787.html