Android 从url获取原始文件数据并显示在ImageView中

Android 从url获取原始文件数据并显示在ImageView中,android,Android,我想显示URL中的图像,该URL为我提供图像的原始数据(png或JPG) 我检查了这个,但没有多大用处 这是我的照片 我正在处理原始数据,但无法看到图像。我不知道如何检查我是否获得了正确的原始数据 这是我的努力 private class DownloadImageTask extends AsyncTask<String, Void, Void> { byte[] bytes; Bitmap picture = null; @Ov

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

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

这是我的照片

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

这是我的努力

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);

        }

    }
私有类下载ImageTask扩展异步任务{
字节[]字节;
位图图片=空;
@凌驾
受保护的Void doInBackground(字符串…URL){
//最终OkHttpClient客户端=新的OkHttpClient();
//
//Request Request=newrequest.Builder()
//.url(url[0])
//.build();
//
//响应=空;
//
//试一试{
//response=client.newCall(request.execute();
//}捕获(IOE异常){
//e.printStackTrace();
//            }
//断言响应!=null;
//if(response.issusccessful()){
//试一试{
//assert response.body()!=null;
//ByteArrayOutputStream bas=新的ByteArrayOutputStream();
//复制(response.body().byteStream(),baos);
//字节=baos.toByteArray();
//picture=BitmapFactory.decodeStream(response.body().ByTestStream());
//}catch(异常e){
//Log.e(“Error”,Objects.requirennull(e.getMessage());
//e.printStackTrace();
//                }
//
//            }
ByteArrayOutputStream outputStream=新建ByteArrayOutputStream();
试一试{
URL=新URL(URL[0]);
byte[]chunk=新字节[4096];
int字节读取;
InputStream=url.openStream();
而((bytesRead=stream.read(chunk))>0){
写入(块,0,字节读取);
}
}捕获(IOE异常){
e、 printStackTrace();
返回null;
}
字节=outputStream.toByteArray();
返回null;
}
@凌驾
受保护的void onPostExecute(void避免){
super.onPostExecute(避免);
如果(字节数!=null){
位图位图=位图工厂.decodeByteArray(字节,0,字节.长度);
setImageBitmap(位图);
}
//设置图像位图(图片);
}
}

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

为此,我建议你:

  • 开始使用您知道正确的原始图像文件,并测试其处理。 有很多。 从标签
    android
    ,我想以下几点可能会有所帮助:

    要将原始图像捕获到文件中,请执行以下操作:

    要在ImageView中显示:

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

  • 将其应用于实际的目标URL

  • 这样,您将知道问题所在。 没有更多的信息,就很难“调试”你的问题


    您还可以检查中的代码。

    确定以下问题:

    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;
         }
     }
    
    
    
    
    类DownLoadImageTask扩展了AsyncTask{
    @凌驾
    受保护的void onPostExecute(位图){
    onPostExecute(位图);
    设置图像位图(位图);
    }
    @凌驾
    受保护位图doInBackground(字符串…字符串){
    试一试{
    OkHttpClient=新的OkHttpClient();
    Request Request=newrequest.Builder().url(字符串[0]).build();
    Response=client.newCall(request.execute();
    if(response.issusccessful()){
    InputStream InputStream=response.body().ByTestStream();
    返回BitmapFactory.decodeStream(inputStream);
    }
    }捕获(IOE异常){
    e、 printStackTrace();
    }
    返回null;
    }
    }
    
    这是我使用的URL


    我可以测试一下。我希望它能帮助您

    您可以使用一个名为毕加索的图书馆,并执行以下操作:

    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'
    

    亲切的问候

    图像的原始数据是什么意思?你不是刚下载了一个像.jpg或.png这样的图像文件吗?不,数据是来自url的原始格式,所以我需要将其转换为图像。你的代码看起来可以下载图像文件。如果您不确定是否接收到正确的字节,请将它们保存到文件中,并检查图像查看器是否可以播放。重复:raw格式是什么意思?您正在尝试将字节转换为位图。你有没有检查bimap==null?@blackapps这里是我从中获取数据的链接谢谢你的回复。你能给我一个在Android中检索原始数据并显示为图像的例子吗?我检查了所有引用,但看不到在Android中显示原始图像的正确方法android@ArpitPatel-如前所述,您的任务可以分为“子任务”。我建议您首先花一些额外的时间来澄清问题所在,而不是要求为整个过程提供完整的代码。这是一种帮助他人帮助你的方法,它增加了你解决问题的机会。我实现了代码,但我没有收到任何错误,所以我只是尝试识别错误。或者,如果我犯了任何错误,我的代码有什么问题。@arpittatel-至于在ImageView中显示,请参阅更新的答案。再次,请帮助缩小问题范围。你能用java上传吗?更新到java,重复创建