【问题标题】:get raw file data from url and display in ImageView从 url 获取原始文件数据并在 ImageView 中显示
【发布时间】:2020-09-02 14:12:17
【问题描述】:

我想显示来自为我提供图像原始数据(png 或 JPG)的 URL 中的图像。

我检查了这个link,但没有多大用处。

这是我的头像link

我正在处理原始数据,但看不到图像。我不确定如何检查我是否获得了正确的原始数据。

这是我的努力

private class DownloadImageTask extends AsyncTask<String, Void, Void> {

        byte[] bytes;
        Bitmap picture = null;

        @Override
        protected Void doInBackground(String... urls) {

//            final OkHttpClient client = new OkHttpClient();
//
//            Request request = new Request.Builder()
//                    .url(urls[0])
//                    .build();
//
//            Response response = null;
//
//            try {
//                response = client.newCall(request).execute();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            assert response != null;
//            if (response.isSuccessful()) {
//                try {
//                    assert response.body() != null;
//                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                    IOUtils.copy(response.body().byteStream(), baos);
//                    bytes = baos.toByteArray();
//                    picture = BitmapFactory.decodeStream(response.body().byteStream());
//                } catch (Exception e) {
//                    Log.e("Error", Objects.requireNonNull(e.getMessage()));
//                    e.printStackTrace();
//                }
//
//            }

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            try {
                URL url = new URL(urls[0]);
                byte[] chunk = new byte[4096];
                int bytesRead;
                InputStream stream = url.openStream();

                while ((bytesRead = stream.read(chunk)) > 0) {
                    outputStream.write(chunk, 0, bytesRead);
                }

            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }

            bytes = outputStream.toByteArray();

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (bytes != null) {
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                cameraView.setImageBitmap(bitmap);
            }
//            cameraView.setImageBitmap(picture);

        }

    }

【问题讨论】:

  • 图像的原始数据是什么意思?你不只是下载一个像.jpg或.png这样的图像文件吗?
  • 不,来自 url 的原始格式的数据,所以我需要将其转换为图像
  • 您的代码看起来可以下载图像文件。如果您不确定接收到正确的字节,请将它们保存到文件中并检查图像查看器是否可以播放它。
  • 重复:原始格式是什么意思?您正在尝试将字节转换为位图。你检查过 bimap==null 吗?
  • @blackapps 这里是我从pastebin.com/tifdC2K3获取数据的链接

标签: android


【解决方案1】:

您的问题在您的工作流程中的位置似乎不确定。 您应该首先确定这一点。 (另外,您没有指定是否绑定到特定的编程语言)。

为此,我建议你:

  1. 开始使用您知道正确的原始图像文件,并测试其处理。 有不少raw image formats。 从标签android来看,我想以下可以帮助:

    要将原始图像捕获到文件中:How to capture raw image from android camera

    在 ImageView 中显示:Can't load image from raw to imageview

    https://gamedev.stackexchange.com/questions/14046/how-can-i-convert-an-image-from-raw-data-in-android-without-any-munging

    https://developer.android.com/reference/android/graphics/ImageFormat

    https://www.androidcentral.com/raw-images-and-android-everything-you-need-know

  2. 尝试从您可以管理的 URL 获取原始图像。

  3. 将此应用于实际的目标 URL。

这样您就可以知道问题出在哪里。 如果没有更多信息,很难“调试”您的问题。

您还可以检查 FOSS projects 中的代码。

【讨论】:

  • 感谢您的回复。你能给我一个在 Android 中检索原始数据并显示为图像的示例吗?
  • 我检查了所有参考资料,但看不到在 android 中显示原始图像的正确方法
  • @ArpitPatel - 如前所述,您的任务可以拆分为“子任务”。我建议您首先花一些时间来澄清您的问题所在,而不是要求整个过程的完整代码。这是帮助他人帮助您的一种方式,它可以增加您解决问题的机会。
  • 我实现了代码但我没有收到任何错误所以我只是想找出错误。或者如果我犯了任何错误,我的代码有什么问题。
  • @ArpitPatel - 至于在 ImageView 中显示,请参阅更新后的答案。再次,请帮助缩小问题范围。
【解决方案2】:

您可以使用名为 Picasso 的库并执行以下操作:

String url = get url from the Async Function and convert it to String
/*if you url has no image format, you could do something like this con convert the uri into a Bitmap*/


public Bitmap getCorrectlyOrientedImage(Context context, Uri uri, int maxWidth)throws IOException {

InputStream input = context.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither = true;//optional
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
try {
      input.close();

    } catch (NullPointerException e) {
            e.printStackTrace();
 }

/*trying to get the right orientation*/
if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) {
            return null;
        }

int originalSize = Math.max(onlyBoundsOptions.outHeight, onlyBoundsOptions.outWidth);

double ratio = (originalSize > maxWidth) ? (originalSize / maxWidth) : 1.0;

Matrix matrix = new Matrix();
        int rotationInDegrees = exifToDegrees(orientation);
        if (orientation != 0) matrix.preRotate(rotationInDegrees);

        int bmpWidth = 0;
        try {
            assert bitmap != null;
            bmpWidth = bitmap.getWidth();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

Bitmap adjustedBitmap = bitmap;
if (bmpWidth > 0)
   adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

return adjustedBitmap;
}

/*Then you has the image in Bitmap, you can use the solution below or if Picasso doesn't allows you to put Bitmap you can pass it directly to the ImageView as a Bitmap.*/

ImageView imageView = view.findViewById(R.id.imageViewId);

/*Then use Picasso to draw the image into the ImageView*/
Picasso.with(context).load(url).fit().into(imageView );

这是build.gradle的依赖,不确定是否是最后一个版本,但你可以试试。

implementation 'com.squareup.picasso:picasso:2.5.2'

亲切的问候!

【讨论】:

  • 此 URL 不提供 jpg 或 png。我不能直接使用 URL 我需要进行处理以将数据转换为 JPG 或 png。
  • 你是如何存储图像的?我认为对于 Picasso,无论 url 如何,它都会找到 url 并尝试将任何内容放入 ImageView,您是否已经尝试过?
  • 我使用第三方 URL 来显示图像,所以我不确定他们如何存储数据。
  • 我更新了我的答案,所以可以将uri转换为Bitmap,然后分配给ImageView,希望它符合您的需求。
  • 我尝试将数据下载为位图,但它不起作用,您可以在我的问题中看到。
【解决方案3】:

确定以下问题:

Using URL to get bytes to load images

我写下了我能参考的东西


class DownLoadImageTask extends AsyncTask<String, Void, Bitmap> {
     @Override
     protected void onPostExecute(Bitmap bitmap) {
         super.onPostExecute(bitmap);
         imageView.setImageBitmap(bitmap);

     }

     @Override
     protected Bitmap doInBackground(String... strings) {
         try {
             OkHttpClient client = new OkHttpClient();
             Request request = new Request.Builder().url(strings[0]).build();
             Response response = client.newCall(request).execute();
             if (response.isSuccessful()) {
                 InputStream inputStream = response.body().byteStream();
                 return BitmapFactory.decodeStream(inputStream);
             }
         } catch (IOException e) {
             e.printStackTrace();
         }
         return null;
     }
 }


这是我使用的网址

https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/440px-Image_created_with_a_mobile_phone.png

https://upload.wikimedia.org/wikipedia/commons/3/3a/Cat03.jpg

我可以测试它。希望对你有帮助

【讨论】:

  • 你能用java上传吗?
  • 更新到java,okhttp请求的重复创建需要自己处理@Arpit Patel
猜你喜欢
  • 2018-01-31
  • 2012-07-12
  • 1970-01-01
  • 2012-05-27
  • 2019-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-19
相关资源
最近更新 更多