开发者

Android image download from server? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.
my logcat---------::


09-07 19:55:51.623: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:55:51.634: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:55:52.033: DEBUG/dalvikvm(1680): GC_FOR_MALLOC freed 1896 objects / 518112 bytes in 97ms
09-07 19:55:52.364: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:55:53.254: DEBUG/dalvikvm(1680): GC_FOR_MALLOC freed 822 objects / 539696 bytes in 67ms
09-07 19:56:01.514: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805085124_wtpa.logo.png
09-07 19:56:01.584: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805084621_wtpa.logo.png
09-07 19:56:01.643: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805025050_chuckie liv.ashx.jpg
09-07 19:56:01.684: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805024007_space vegas.ashx.jpg
09-07 19:56:01.914: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:01.953: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:02.714: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:02.754: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805023407_blush vegas.ashx.jpg
09-07 19:56:02.834: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805022856_Savoy vegas.ashx.jpg
09-07 19:56:02.944: DEBUG/dalvikvm(1680): GC_FOR_MALLOC freed 1058 objects / 490016 bytes in 80ms
09-07 19:56:02.944: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:02.944: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:03.894: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:03.923: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110808101519_DSC0028-Ti.jpg
09-07 19:56:04.104: INFO/System.out(1680): ImageUrl :: http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110729152914_wtpa.logo.png
09-07 19:56:04.604: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:04.634: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:05.004: DEBUG/dalvikvm(1680): GC_FOR_MALLOC freed 966 objects / 515008 bytes in 80ms
09-07 19:56:05.404: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:05.434: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:05.464: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null
09-07 19:56:06.194: DEBUG/skia(1680): --- SkImageDecoder::Factory returned null

my code is ::

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Map;
import java.util.Stack;
import java.util.WeakHashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.EventLogTags.Description;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class ImageLoader {

    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    private ProgressBar indicator;

    public ImageLoader(Context context) {

        photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);
        fileCache = new FileCache(context);
    }

    public void DisplayImage(String url, Context activity, ImageView imageView,
            ProgressBar pbar) {

        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);

        if (bitmap != null) {
            this.indicator = pbar;
            indicator.setVisibility(View.INVISIBLE);
            imageView.setImageBitmap(bitmap);
        } else {
            this.indicator = pbar;
            indicator.setVisibility(View.INVISIBLE);
            queuePhoto(url, activity, imageView);
            imageView.setImageBitmap(null);
        }
    }

    private void queuePhoto(String url, Context 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) {
        File f = fileCache.getFile(url);

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

        // from web
        try {

            HttpGet httpRequest = null;

            try {


                int pos = url.lastIndexOf('/') + 1;
                URI uri = new URI(url.substring(0, pos)
                        + URLEncoder.encode(url.substring(pos), "UTF-8"));
               //URL imgUrl = new URL(decodeUrl);
                httpRequest = new HttpGet(uri);
            } catch (URISyntaxException e) {
                System.out.println("Error ::" + e.toString());
            开发者_开发百科    e.printStackTrace();
            }

            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = (HttpResponse) httpclient
                    .execute(httpRequest);

            HttpEntity entity = response.getEntity();
            BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
            InputStream instream = bufHttpEntity.getContent();
            Bitmap bm = BitmapFactory.decodeStream(instream);

            /*
             * Bitmap bitmap = null; URL imageUrl = new URL(url);
             * HttpURLConnection conn = (HttpURLConnection) imageUrl
             * .openConnection(); conn.connect(); conn.getDoOutput();
             * 
             * 
             * conn.setConnectTimeout(30000); conn.setReadTimeout(30000);
             * 
             * InputStream is = conn.getInputStream();
             * 
             * OutputStream os = new FileOutputStream(f); Utils.CopyStream(is,
             * os); os.close(); bitmap = decodeFile(f); return bitmap;
             */
            return bm;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private Bitmap gonextUrl(String url) {
        Bitmap bm = null;
        try {

            URL imgUrl = new URL(url);
            HttpGet httpRequest = new HttpGet(imgUrl.toURI());

            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = (HttpResponse) httpclient
                    .execute(httpRequest);

            HttpEntity entity = response.getEntity();
            BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
            InputStream instream = bufHttpEntity.getContent();
            bm = BitmapFactory.decodeStream(instream);

            return bm;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }

    // 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 = 70;
            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 *= 2;
            }

            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) {

                    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();
                        }
                        Bitmap bmp = getBitmap(photoToLoad.url);
                        memoryCache.put(photoToLoad.url, bmp);
                        String tag = imageViews.get(photoToLoad.imageView);
                        if (tag != null && tag.equals(photoToLoad.url)) {

                            BitmapDisplayer bd = new BitmapDisplayer(bmp,
                                    photoToLoad.imageView, indicator);
                            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;

        // private ProgressBar indicator1;

        public BitmapDisplayer(Bitmap b, ImageView i, ProgressBar indicator) {
            this.bitmap = b;
            this.imageView = i;
            // this.indicator1 = indicator;
        }

        public void run() {
            if (bitmap != null) {
                // indicator1.setVisibility(View.INVISIBLE);
                imageView.setImageBitmap(bitmap);
            } else
                imageView.setImageBitmap(null);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}


call this function loadImageFromUrl(" http://www.heresmyparty.com/cms/components/com_chronocontact/uploads/add_event_form/20110805085124_wtpa.logo.png") to get image bitmap from imageurl

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

this is the class for PatchInputStream

public class PatchInputStream extends FilterInputStream {
          public PatchInputStream(InputStream in) {
            super(in);
          }
          public long skip(long n) throws IOException {
            long m = 0L;
            while (m < n) {
              long _m = in.skip(n-m);
              if (_m == 0L) break;
              m += _m;
            }
            return m;
          }
        }

You can also modify your code to prevent error.Just you need to add PatchInputStream(inputStream) in BitmapFactory.decodeStream(new PatchInputStream(inputStream), null,bpo );

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜