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

Java 将图像从服务器下载到android并在imageview中显示,java,android,Java,Android,我有一个服务器(我使用GlassFish)。我能够通过http将Json或XML等发送到我的android设备。我看到了一个从android设备上传图片到服务器的例子。它将我拾取的图像转换为字节,转换为字符串并返回到我的服务器。所以我可以把它放在我的电脑(服务器)上。 现在我只想要相反的结果:从我的PC上获取一张图片,并使用URL将图像(此处的位图)获取到imageview。但在调试过程中,bmp似乎为“null”。谷歌说这是因为我的图像不是有效的位图(所以我的服务器编码可能有问题?)。 我需要

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

服务器代码:

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;

    }

}
这是android端(android studio):

公共类XMLTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字符串…URL){
HttpURLConnection=null;
BufferedReader reader=null;
试一试{
java.net.URL URL=新URL(URL[0]);
connection=(HttpURLConnection)url.openConnection();
connection.connect();
InputStream=connection.getInputStream();
reader=新的BufferedReader(新的InputStreamReader(流));
StringBuffer=新的StringBuffer();
字符串行=”;
而((line=reader.readLine())!=null){
buffer.append(行);
}
返回buffer.toString();
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
if(连接!=null){
连接断开();
}
试一试{
if(读卡器!=null){
reader.close();
}
}捕获(IOE异常){
e、 printStackTrace();
}
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串行){
super.onPostExecute(行);
字节[]imageByteArray=Base64.decode(第行,Base64.DEFAULT);
试一试{
位图bmp=BitmapFactory.decodeByteArray(imageByteArray,0,imageByteArray.length);
设置图像位图(bmp);
}捕获(例外e){
Log.d(“tag”,例如toString());
}
}
}
为什么不使用

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

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

你为什么不使用

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

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


尝试使用
Base64.encodeBase64String(imageData)
不使用
urlsafetstring
尝试使用
Base64.encodeBase64String(imageData)
不使用
urlsafetstring

您可以使用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();
                                    }
                                }
                            }
                        });

您可以使用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();
                                    }
                                }
                            }
                        });

您是否尝试过
HttpURlConnection

下面是一个示例代码:

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);
            }
    }
私有类SendHttpRequestTask扩展了AsyncTask{
@凌驾
受保护位图doInBackground(字符串…参数){
试一试{
URL=新URL(“http://xxx.xxx.xxx/image.jpg");
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream输入=连接。getInputStream();
位图myBitmap=BitmapFactory.decodeStream(输入);
返回我的位图;
}捕获(例外e){
Log.d(标记,例如getMessage());
}
返回null;
}
@凌驾
受保护的void onPostExecute(位图结果){
ImageView ImageView=(ImageView)findViewById(图像视图的ID);
设置图像位图(结果);
}
}

我希望我能帮你

你试过
HttpURlConnection

下面是一个示例代码:

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);
            }
    }
私有类SendHttpRequestTask扩展了AsyncTask{
@凌驾
受保护位图doInBackground(字符串…参数){
试一试{
URL=新URL(“http://xxx.xxx.xxx/image.jpg");
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream输入=连接。getInputStream();
位图myBitmap=BitmapFactory.decodeStream(输入);
返回我的位图;
}捕获(例外e){
Log.d(标记,例如getMessage());
}
返回null;
}
@凌驾
受保护的void onPostExecute(位图结果){
ImageView ImageView=(ImageView)findViewById(图像视图的ID);
设置图像位图(结果);
}
}

我希望我能帮上忙

如果有人也试图用我的方式做这件事,这很有效:

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

如果有人也试图用我的方式来做,这是有效的:

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

我希望这段代码是有用的

转到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);
}
public类MainActivity扩展了AppCompatActivity{
图像视图图像视图;
公共void下载图像(视图)
{
Log.i(“按钮”、“点击”);
DownloadImage任务=新建DownloadImage();
位图结果=空;
试一试{
结果=任务。执行(“https://vignette.wikia.nocookie.net/disney/images/0/0a/ElsaPose.png/revision/latest?cb=20170221004839).get();
}
捕获(中断异常|执行异常e){
e、 printStackTrace();
}
设置图像位图(结果);
}
公共课做什么
       <uses-permission android:name="android.permission.INTERNET"/>