4

GridView で画像を表示するアプリを実行しています。サーバーから 20 枚の画像を取得しています。各画像の解像度は 720*540 です。JSON 解析を使用して URL を取得し、以下のコードを使用してビットマップに変換して画像を設定しました。

public static Bitmap loadImageFromUrl(String url) {
    InputStream inputStream;Bitmap b;
    try {
        inputStream = (InputStream) new URL(url).getContent();
        BitmapFactory.Options bpo=  new BitmapFactory.Options();
        if(bpo.outWidth>500) {
            bpo.inSampleSize=8;
            b=BitmapFactory.decodeStream(inputStream, null,bpo );
        } else {
            bpo.inSampleSize=2;
            b=BitmapFactory.decodeStream(inputStream, null,bpo );
        }
        return  b;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

アプリは正常に動作していますが、画像の読み込みに時間がかかりすぎています。私のアプリが遅くなったように。画像の解像度を下げる必要がありますか?

問題から抜け出す方法は?

4

5 に答える 5

8

このような解像度の 20 個の画像を読み込むためにグリッド ビューを実行している場合は、次のことをお勧めします。

  1. 画像のサイズを確実に縮小します。タブレットをターゲットにしている場合を除き、ほとんどのスマートフォンは 20 枚の画像でその解像度を達成できないため、問題ありません。

  2. 可能であれば画像をキャッシュします。

  3. 別のスレッドで画像をダウンロードします。HashMap を保存すると、イメージ ファイル名またはその他の形式の ID をキーとしてすべてのイメージビューを配置するだけで簡単になります。画像がダウンロードされたときにハンドラーにメッセージを送信し、デコード後にビューを更新します。ビューを直接取得できます。それらがまだウィンドウ内にあるかどうかを確認することを忘れないでください。このようにして、画像が次々とすばやく表示されます。画像のマルチスレッド化が役立つとは思いません。別のスレッドを使用して「画像をプッシュ」し、メインの UI スレッドが更新されるようにしてください。ユーザーエクスペリエンスは大幅に向上します。

お役に立てれば。

---いくつかの実装、私は今、完全なコードを持っていません---

ビューと入ってくるデータを一致させるデータ構造を持っています。ここでは非常に便利です。

private HashMap<String,ImageView> pictures;

画像 URL のリストを取得したら、それらを繰り返し処理します。

 pictures.put(id,view);
        try{
            FileInputStream in = openFileInput(id);
            Bitmap bitmap = null;
            bitmap = BitmapFactory.decodeStream(in, null, null);
        view.setImageBitmap(bitmap);
        }catch(Exception e){
            new Thread(new PictureGetter(this,mHandler,id)).start();
        }

(ここでは、画像がまだキャッシュされていない場合、画像ゲッターは単純に画像を取得してキャッシュします)

画像ビューを更新するコード:

 if(id!=null){
        ImageView iv = pictures.get(id);
        if(iv!=null){
            try{
                FileInputStream in = openFileInput(id);
                Bitmap bitmap = null;
                bitmap = BitmapFactory.decodeStream(in, null, null);
                iv.setImageBitmap(bitmap);
            }catch(Exception e){
        }
    }
于 2011-08-09T06:25:48.210 に答える
1

私のAndroidアプリでも同じ問題があります。大きなサイズの画像からビットマップをデコードし、imageBitmap として画像ビューに設定すると、おそらくアプリケーションの速度が低下し、数回試行すると「メモリ不足の例外」が発生します。

この問題を処理するには、次の 2 つの方法があります。 1- ファイルからデコードするときにビットマップ サイズを小さくする 2- イメージ ライブラリを使用する。

私は 2 番目の方法を好み、Universal Image Loader を使用しました。https://github.com/nostra13/Android-Universal-Image-Loader

String url = "file://" + your_file_path
com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(url, ivPicture, options);
于 2014-10-21T08:46:09.280 に答える
1

読み込み時間のほとんどは、画像のサイズと組み合わされた大量の画像が原因であると推測しています。

考えられる解決策は 2 つあります。

  1. 画像のサイズを変更するか、画像の品質を下げて、ファイルサイズが 75kb 程度以下になるようにします。

  2. マルチスレッドを使用して、一度に複数の画像を取得します。ユーザーの接続が非常に遅い場合、これは役に立たないかもしれませんが、これを十分に小さいファイルサイズと組み合わせると、十分に役立つかもしれません. デバイスの現在の帯域幅を特定し、それに基づいて実行するスレッドの数を決定することができます。

例: それぞれ 75KB の 20 個のイメージと 200 KB/秒の利用可能な接続 = 3 つまたは 4 つの同時スレッド。

お役に立てれば。

于 2011-08-09T05:51:33.273 に答える
0
 public class clothImageLoader {

// the simplest in-memory cache implementation. This should be replaced with
// something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
// public static HashMap<String, Bitmap> cache = new HashMap<String,
// Bitmap>();

private static File cacheDir;

public clothImageLoader(Context context) {
    // Make the background thead low priority. This way it will not affect
    // the UI performance
    photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);

    // Find the dir to save cached images
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        // cacheDir=new
        // File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
        cacheDir = new File(ConstValue.MY_ClothBitmap_DIR);
    else
        cacheDir = context.getCacheDir();
    if (!cacheDir.exists())
        cacheDir.mkdirs();
}

final int stub_id = R.drawable.icon;

public void DisplayImage(String url, Activity activity, ImageView imageView) {
    if (ConstValue.ClothRoomcache.containsKey(url))
        imageView.setImageBitmap(ConstValue.ClothRoomcache.get(url));
    else {
        queuePhoto(url, activity, imageView);
        imageView.setImageResource(stub_id);
    }
}

private void queuePhoto(String url, Activity activity, ImageView imageView) {
    // This ImageView may be used for other images before. So there may be
    // some old tasks in the queue. We need to discard them.
    photosQueue.Clean(imageView);
    PhotoToLoad p = new PhotoToLoad(url, imageView);
    synchronized (photosQueue.photosToLoad) {
        photosQueue.photosToLoad.push(p);
        photosQueue.photosToLoad.notifyAll();
    }

    // start thread if it's not started yet
    if (photoLoaderThread.getState() == Thread.State.NEW)
        photoLoaderThread.start();
}

private Bitmap getBitmap(String url) {
    // I identify images by hashcode. Not a perfect solution, good for the
    // demo.
    String filename = String.valueOf(url.hashCode());
    File f = new File(cacheDir, filename);

    // from SD cache
    Bitmap b = decodeFile(f);
    if (b != null)
        return b;

    // from web
    try {
        Bitmap bitmap = null;
        /*
         * InputStream is=new URL(url).openStream(); OutputStream os = new
         * FileOutputStream(f); Utils.CopyStream(is, os); os.close();
         */
        URL url1 = new URL(url);
        bitmap = decodeFile(f);
        /* Open a connection to that URL. */
        URLConnection ucon = url1.openConnection();

        /*
         * Define InputStreams to read from the URLConnection.
         */
        InputStream is = ucon.getInputStream();
        // FlushedInputStream a = new FlushedInputStream(is);
        BufferedInputStream bis = new BufferedInputStream(is);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();

        bitmap = decodeFile(f);
        return bitmap;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
    try {
        // decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f), null, o);
        // Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE = ConstValue.bmpSize;
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale++;
        }

        // decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {
    }
    return null;
}

// Task for the queue
private class PhotoToLoad {
    public String url;
    public ImageView imageView;

    public PhotoToLoad(String u, ImageView i) {
        url = u;
        imageView = i;
    }
}

PhotosQueue photosQueue = new PhotosQueue();

public void stopThread() {
    photoLoaderThread.interrupt();
}

// stores list of photos to download
class PhotosQueue {
    private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();

    // removes all instances of this ImageView
    public void Clean(ImageView image) {
        for (int j = 0; j < photosToLoad.size();) {
            if (photosToLoad.get(j).imageView == image)
                photosToLoad.remove(j);
            else
                ++j;
        }
    }
}

class PhotosLoader extends Thread {
    public void run() {
        try {
            while (true) {
                // thread waits until there are any images to load in the
                // queue
                if (photosQueue.photosToLoad.size() == 0)
                    synchronized (photosQueue.photosToLoad) {
                        photosQueue.photosToLoad.wait();
                    }
                if (photosQueue.photosToLoad.size() != 0) {
                    PhotoToLoad photoToLoad;
                    synchronized (photosQueue.photosToLoad) {
                        photoToLoad = photosQueue.photosToLoad.pop();

                        // photoToLoad=photosQueue.photosToLoad.get(0);
                        // photosQueue.photosToLoad.remove(photoToLoad);
                    }
                    Bitmap bmp = getBitmap(photoToLoad.url);
                    ConstValue.ClothRoomcache.put(photoToLoad.url, bmp);
                    if (((String) photoToLoad.imageView.getTag()).equals(photoToLoad.url)) {
                        BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad.imageView);
                        Activity a = (Activity) photoToLoad.imageView.getContext();
                        a.runOnUiThread(bd);
                    }
                }
                if (Thread.interrupted())
                    break;
            }
        } catch (InterruptedException e) {
            // allow thread to exit
        }
    }
}

PhotosLoader photoLoaderThread = new PhotosLoader();

// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
    Bitmap bitmap;
    ImageView imageView;

    public BitmapDisplayer(Bitmap b, ImageView i) {
        bitmap = b;
        imageView = i;
    }

    public void run() {
        if (bitmap != null)
            imageView.setImageBitmap(bitmap);
        else
            imageView.setImageResource(stub_id);
    }
}

public static void clearCache() {
    // clear memory cache
    ConstValue.ClothRoomcache.clear();

    // clear SD cache
    File[] files = cacheDir.listFiles();
    for (File f : files)
        f.delete();
}

public class FlushedInputStream extends FilterInputStream {
    public FlushedInputStream(InputStream inputStream) {
        super(inputStream);
    }

    @Override
    public long skip(long n) throws IOException {
        long totalBytesSkipped = 0L;
        while (totalBytesSkipped < n) {
            long bytesSkipped = in.skip(n - totalBytesSkipped);
            if (bytesSkipped == 0L) {
                int a = read();
                if (a < 0) {
                    break; // we reached EOF
                } else {
                    bytesSkipped = 1; // we read one byte
                }
            }
            totalBytesSkipped += bytesSkipped;
        }
        return totalBytesSkipped;
    }
}

}

gridView getView メソッドでメソッドを呼び出すと、次のようになります。

holder.image.setTag(ChoseInfo.get(position).getLink());
        imageLoader.DisplayImage(ChoseInfo.get(position).getLink(), activity, holder.image);

ChoseInfo.get(位置).getLink())

ここgetLink()にインターネットリンクがあります。

于 2011-11-23T08:51:15.547 に答える