Android では、次の最も簡単な方法は何ですか。
- リモート サーバーからイメージを読み込みます。
- ImageView で表示します。
これは私が実際にアプリケーションで使用した方法であり、それが機能することを知っています:
try {
URL thumb_u = new URL("http://www.example.com/image.jpg");
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
myImageView.setImageDrawable(thumb_d);
}
catch (Exception e) {
// handle it
}
2番目のパラメーターが何であるかはわかりませんDrawable.createFromStream
が、渡すのはうまくいく"src"
ようです。ドキュメントは実際には何も言っていないので、誰かが知っている場合は、光を当ててください。
これまでのところ最も簡単な方法は、単純なイメージ リトリーバーを作成することです。
public Bitmap getRemoteImage(final URL aURL) {
try {
final URLConnection conn = aURL.openConnection();
conn.connect();
final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
final Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
return bm;
} catch (IOException e) {}
return null;
}
次に、メソッドに URL を指定するだけで、Bitmap
. 次に、setImageBitmap
からのメソッドを使用しImageView
て画像を表示するだけです。
ここで両方の答えに注意してください - どちらもOutOfMemoryException
. デスクトップの壁紙などの大きな画像をダウンロードして、アプリケーションをテストします。明確にするために、問題のある行は次のとおりです。
final Bitmap bm = BitmapFactory.decodeStream(bis);
と
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
Felix の答えは catch{} ステートメントでそれをキャッチし、そこで何かを行うことができます。
OutOfMemoryException
エラーを回避する方法は次のとおりです。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(is, null, options);
} catch (OutOfMemoryError ome) {
// TODO - return default image or put this in a loop,
// and continue increasing the inSampleSize until we don't
// run out of memory
}
そして、これが私のコードでのこれに関する私のコメントです
/**
* Showing a full-resolution preview is a fast-track to an
* OutOfMemoryException. Therefore, we downsample the preview image. Android
* docs recommend using a power of 2 to downsample
*
* @see <a
* href="https://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue/823966#823966">StackOverflow
* post discussing OutOfMemoryException</a>
* @see <a
* href="http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize">Android
* docs explaining BitmapFactory.Options#inSampleSize</a>
*
*/
このライブラリを試すこともできます: https://github.com/codingfingers/fastimage
同じパターンのプロジェクトがほとんどなく、ライブラリが登場したとき;)他の人と共有してみませんか...
これは簡単です:
この依存関係を gradle スクリプトに追加します。
implementation 'com.squareup.picasso:picasso:2.71828'
*2.71828 は現在のバージョンです
次に、画像ビューに対してこれを行います。
Picasso.get().load(pictureURL).into(imageView);