Java 从服务器下载图像到android并在imageview中显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43557167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:00:16  来源:igfitidea点击:

Download a image from server to android and show in imageview

javaandroid

提问by Axxeption

I have an server (i use GlassFish). I am able to send Json or XML etc. with http to my android device. I saw an example to upload a picture from my android device to the server. That converts my picked image to byte, converts to String and back at my server. So i can put it on my PC (server). Now i just want the opposite: get a picture from my PC and with the URL get the image (bitmap here) to imageview. but with debugging bmp seems to be "null". google says its because my image is not a valid bitmap (so maybe something is wrong at my server encoding?). What does i need to change to this code to get it working?

我有一台服务器(我使用 GlassFish)。我可以使用 http 将 Json 或 XML 等发送到我的 android 设备。我看到了一个将图片从我的 android 设备上传到服务器的示例。这将我选择的图像转换为字节,转换为字符串并返回到我的服务器。所以我可以把它放在我的电脑(服务器)上。现在我只想要相反的:从我的 PC 获取一张图片,并使用 URL 将图像(这里的位图)获取到 imageview。但调试 bmp 似乎是“空”。谷歌说这是因为我的图像不是有效的位图(所以我的服务器编码可能有问题?)。我需要对此代码进行哪些更改才能使其正常工作?

Server code:

服务器代码:

public class getImage{
    String imageDataString = null;

    @GET
    @Path("imageid/{id}")
    public String findImageById(@PathParam("id") Integer id) {
        //todo: schrijf een query voor het juiste pad te krijgen!
        System.out.println("in findImageById");
        File file = new File("C:\Users\vulst\Desktop\MatchIDImages\Results\R\Tensile_Hole_2177N.tif_r.bmp");

        try{
            // Reading a Image file from file system
            FileInputStream imageInFile = new FileInputStream(file);
            byte imageData[] = new byte[(int) file.length()];
            imageInFile.read(imageData);

            // Converting Image byte array into Base64 String
            imageDataString = Base64.encodeBase64URLSafeString(imageData);
            imageInFile.close();

            System.out.println("Image Successfully Manipulated!");
        } catch (FileNotFoundException e) {
            System.out.println("Image not found" + e);
        } catch (IOException ioe) {
            System.out.println("Exception while reading the Image " + ioe);
        }
        return imageDataString;

    }

}

and this is the android side (android studio):

这是android端(android studio):

public class XMLTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... urls) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            java.net.URL url = new URL(urls[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            return buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String line) {
        super.onPostExecute(line);
        byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);

        try {
            Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
            ivFoto.setImageBitmap(bmp);
        }catch (Exception e){
            Log.d("tag" , e.toString());
        }
    }
}

采纳答案by Melchizedek

Have you tried HttpURlConnection?

你试过HttpURlConnection吗?

Here's a sample code:

这是一个示例代码:

private class SendHttpRequestTask extends AsyncTask<String, Void, Bitmap> {
            @Override
            protected Bitmap doInBackground(String... params) {
                try {
                    URL url = new URL("http://xxx.xxx.xxx/image.jpg");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    Bitmap myBitmap = BitmapFactory.decodeStream(input);
                    return myBitmap;
                }catch (Exception e){
                    Log.d(TAG,e.getMessage());
                }
                return null;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                    ImageView imageView = (ImageView) findViewById(ID OF YOUR IMAGE VIEW);
                    imageView.setImageBitmap(result);
            }
    }

I hope i could help

我希望我能帮上忙

回答by Anggrayudi H

Why don't you use Glide?

你为什么不使用Glide

For build.gradlein your app module:

对于build.gradle您的应用程序模块:

dependencies {
    compile 'com.github.bumptech.glide:glide:3.7.0'
    ...
}

Then:

然后:

Glide  
    .with(context) // replace with 'this' if it's in activity
    .load("http://www.google.com/.../image.gif")
    .into(R.id.imageView);

回答by chalitha geekiyanage

Try using Base64.encodeBase64String(imageData)with out using the URLSafeString.

尝试使用Base64.encodeBase64String(imageData)而不使用URLSafeString.

回答by Shashank Singh

You can use Glide it is simplest way to load image This is how you can save image

您可以使用 Glide 这是加载图像的最简单方法 这是保存图像的方法

Glide.with(context)
                        .load(image)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                                String name = new Date().toString() + ".jpg";

                                imageName = imageName + name.replaceAll("\s+", "");
                                Log.d(TAG, "onResourceReady: imageName = " + imageName);
                                ContextWrapper contextWrapper = new ContextWrapper(mContext);
                                File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);

                                File myPath = new File(directory, imageName);


                                FileOutputStream fileOutputStream = null;
                                try {
                                    fileOutputStream = new FileOutputStream(myPath);
                                    resource.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    try {
                                        fileOutputStream.close();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });

and this is how you can read the image

这就是你如何阅读图像

ContextWrapper contextWrapper = new ContextWrapper(mContext);
    File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);
    String path = directory.getAbsolutePath();
    path = path + "/" + imageName;
    Glide.with(mContext).load(path).into(your imageview);

回答by Axxeption

If there are people who are also trying to do it my way, this is working:

如果有人也试图按照我的方式做,这很有效:

public class XMLTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... urls) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            java.net.URL url = new URL(urls[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            return buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String line) {
        super.onPostExecute(line);
        byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);
        try {
            Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
            ivFoto.setImageBitmap(bmp);
        }catch (Exception e){
            Log.d("tag" , e.toString());
        }
    }
}


@Stateless
@Path("getImage")
public class getImage {

    //todo: capture error inandroid +  take just path!
    String imageDataString = null;

    @GET
    @Path("imageid/{id}")
    public String findImageById(@PathParam("id") Integer id) {
        //todo: schrijf een query voor het juiste pad te krijgen!
        System.out.println("in findImageById");
        File file = new File("C:\Users\vulst\Desktop\MatchIDImages\Results\R\Tensile_Hole_2177N.tif_r.bmp");

        try{
            // Reading a Image file from file system
            FileInputStream imageInFile = new FileInputStream(file);
            byte imageData[] = new byte[(int) file.length()];
            imageInFile.read(imageData);

            // Converting Image byte array into Base64 String
            imageDataString = Base64.encodeBase64String(imageData);
            imageInFile.close();

            System.out.println("Image Successfully Manipulated!");
        } catch (FileNotFoundException e) {
            System.out.println("Image not found" + e);
        } catch (IOException ioe) {
            System.out.println("Exception while reading the Image " + ioe);
        }
        return imageDataString;

    }
}

回答by vasavi manchikanti

I hope this code is useful.

我希望这段代码有用。

go to your MainActivity.java and try this code:

转到您的 MainActivity.java 并尝试以下代码:

public class MainActivity extends AppCompatActivity {
ImageView imageView;

public void downloadImage(View view)
{

    Log.i("Button","Tapped");

    DownloadImage task = new DownloadImage();
    Bitmap result = null;
    try {
        result = task.execute("https://vignette.wikia.nocookie.net/disney/images/0/0a/ElsaPose.png/revision/latest?cb=20170221004839").get();
    }
    catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    imageView.setImageBitmap(result);

}

public class DownloadImage extends AsyncTask<String, Void, Bitmap>
{


    @Override
    protected Bitmap doInBackground(String... imageurls) {


        URL url;
        HttpURLConnection httpURLConnection;

        try {
            url = new URL(imageurls[0]);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            InputStream in =httpURLConnection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(in);
            return myBitmap;

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



    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imageView = (ImageView)findViewById(R.id.imageView);
}

}

}

Don't forget to add this piece of code in your AndroidManifest.xml

不要忘记在您的 AndroidManifest.xml 中添加这段代码

       <uses-permission android:name="android.permission.INTERNET"/>