2017-04-22 65 views
0

我有一臺服務器(我使用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,你可以加載它? –

回答

1

您已經嘗試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

0

你爲什麼不使用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

0

嘗試使用URLSafeString使用Base64.encodeBase64String(imageData)跟了出去。

+0

感謝您的回答!我可以試試這個:imageDataString = Base64.encodeBase64String(imageData);但是你所說的在Netbeans圖書館中並不存在:也許有錯?我使用這個導入:import org.apache.commons.codec.binary.Base64; – lambotje

+0

對不起,我更新了它需要的編碼'encodeBase64String'。它對你有用嗎? –

+0

不,這不是訣竅... – lambotje

1

您可以使用滑翔它加載圖像 這是如何保存的圖像

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

0

如果還有人誰也嘗試做自己的路,這是工作:

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; 

    } 
} 
0

我希望這個代碼是非常有用的。

去你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"/> 
相關問題