想要从localhost Api提取字节数据图像并在imageview中显示

时间:2019-04-08 12:04:26

标签: android

在我的项目中,有一个本地服务器,我需要从中获取二进制数据形式的图像

我曾尝试使用base64string来图像代码,但无法获取图像

ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Bitmap bitmap = (Bitmap) BitmapFactory.decodeFile(url);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

    //decode base64 string to image
    imageBytes = Base64.decode(imageString, Base64.DEFAULT);
    Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
    image.setImageBitmap(decodedImage);

1 个答案:

答案 0 :(得分:0)

使用AsyncTask来获取图像并将其设置为位图,然后将位图设置为ImageView。试试这个:

@SuppressLint("StaticFieldLeak") AsyncTask<Void, Void, Bitmap> setImageFromUrl = new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                Bitmap bmp = null;
                try {

                    HttpGet httpRequest = new HttpGet(URI.create(IMAGE_ENDPOINT_URL));
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpResponse response = httpclient.execute(httpRequest);
                    HttpEntity entity = response.getEntity();
                    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
                    bmp = BitmapFactory.decodeStream(bufHttpEntity.getContent());
                    httpRequest.abort();

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return bmp;
            }

            protected void onPostExecute(Bitmap bmp) {
                if (bmp != null) {

                    mImageView.setImageBitmap(bmp);

                }

            }
        };