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

问题描述:

我有一台服务器(我使用GlassFish)。我能够发送JSON或XML等与http到我的Android设备。我看到一个例子,从android设备上传一张照片到服务器。这将我选择的图像转换为字节,转换为字符串并返回到我的服务器。所以我可以把它放在我的电脑(服务器)上。 现在我只是想要相反的:从我的电脑获取图片并使用URL获取图像(位图)到imageview。但用调试bmp似乎是“空”。谷歌说,因为我的形象不是一个有效的位图(所以也许我的服务器编码是错的?)。 我需要更改此代码才能使其工作?将图片从服务器下载到android并在imageview中显示

Server代码:

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侧(机器人工作室):

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

我们需要你的日志! –

+0

使用https://github.com/square/picasso。毕加索易于使用。 – MASh

+0

我没有看到返回编码的图像点。为什么你不只是在Android部分返回url,你可以加载它? –

您已经尝试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); 
      } 
    } 

我希望我能帮助

+1

这确实有效,但我已经有了这个。感谢您的回答 – lambotje

+0

很高兴帮助队友:) – Melchizedek

你为什么不使用Glide

对于您的应用模块中build.gradle

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

然后:

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

是的,我已经把它用于以前的事情,但我使用毕加索。但我怎么可以在你的例子中做出这样的链接:.load(“http://www.google.com/.../image.gif”)因为该文件来自我的PC – lambotje

+0

@lambotje,你可以'将您的Android设备与电脑连接起来,因为它们都在不同的操作系统中。将图像放入SD卡中,然后就可以工作了。 –

+0

谢谢,我知道你在说什么,但我有我的数据库中的每张图片的路径,所以我会在最后得到链接的路径,并将该图片发送到我的Android设备。所以通常OS没有什么可以看到这个?希望你能帮助! – lambotje

尝试使用URLSafeString使用Base64.encodeBase64String(imageData)跟了出去。

+0

感谢您的回答!我可以试试这个:imageDataString = Base64.encodeBase64String(imageData);但是你所说的在Netbeans图书馆中并不存在:也许有错?我使用这个导入:import org.apache.commons.codec.binary.Base64; – lambotje

+0

对不起,我更新了它需要的编码'encodeBase64String'。它对你有用吗? –

+0

不,这不是诀窍... – lambotje

您可以使用滑翔它加载图像 这是如何保存的图像

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

最简单的方法,这是你可以读取图像

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

抱歉,但我不明白。我可以重复我的问题:我想在我的应用程序上显示来自PC的图片,而不使用绘图..?感谢您的回答 – lambotje

+0

或者您可以给我一个清晰的视频来使用Glide做到这一点吗? – lambotje

+0

谢谢Shashank,这一行[name.replaceAll(“\\ s +”,“”)]保存了我的头发。 – iSofia

如果还有人谁也尝试做自己的路,这是工作:

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; 

    } 
} 

我希望这个代码是非常有用的。

去你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); 
} 

}

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

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