2017-04-22 10 views
0

私はサーバーを持っています(私はGlassFishを使用しています)。私は私のアンドロイドデバイスにhttpでJsonやXMLなどを送ることができます。私はアンドロイドデバイスからサーバーに画像をアップロードする例を見ました。これは、私の選択した画像をバイトに変換し、Stringに変換して、私のサーバに戻します。だから私は自分のPC(サーバー)に置くことができます。 今私はちょうど反対が欲しい:私のPCから画像を取得し、URLを使って画像(ビットマップ)を画像ビューに取得します。しかし、デバッグbmpと "null"と思われる。私のイメージは有効なビットマップではないので、googleはそのことを言います(私のサーバーのエンコーディングでは何かが間違っていますか?)。 動作させるには、このコードを変更する必要がありますか?サーバーからアンドロイドにイメージをダウンロードしてイメージビューで表示

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側(アンドロイドスタジオ)である:あなたがGlideを使用していないのはなぜ

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

?アプリのモジュールで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デバイスとPCをリンクする必要はありません。あなたのSDカードにイメージを置くと、それは動作します。 –

+0

ありがとう、私はあなたが言っていることを知っているが、私はデータベース内の各画像へのパスを持っているので、私は最後に何をするだろう:パスへのリンクを取得し、だから、通常、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

申し訳ありませんがわかりません。私は私の質問を繰り返すことができます:私はdrawableを使用せずに私のアプリで自分のPCから写真を表示したい..?あなたの答えをお寄せいただきありがとうございます – lambotje

+0

グライドを使ってこれを行うための明確なビデオを教えてください。 – 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"/> 
関連する問題