关闭

根据url下载一张大小为1M左右的图片,然后用个ImageView显示出来。不爆内存的哦!!!

标签: urlexceptionstringnullpathbyte
2921人阅读 评论(0) 收藏 举报
public class NewsletterInfoManager  extends TabManager {

	private static final NewsletterInfoManager INSTANCE = new NewsletterInfoManager();

	private ImageFileCache imageFileCache = new ImageFileCache();
	private Handler mHandler;
	private String newsLetterUrl;
    private Bitmap bitmap = null;

	protected NewsletterInfoManager() {
		mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				if(bitmap!=null && !bitmap.isRecycled()){
					bitmap.recycle();
				}
				bitmap = imageFileCache.getBigImage(newsLetterUrl);
				getDC().loadImage(bitmap);
				getDC().getNewsletterProgressBar().setVisibility(View.INVISIBLE);
			}

		};
	}

	public static NewsletterInfoManager getInstance() {
		return INSTANCE;
	}


	@Override
	protected BaseDC createDC() {
		return new NewsletterDC(context, R.layout.newsletter_info2, this);
	}

	public NewsletterDC getDC() {
		return (NewsletterDC) super.getDC();
	}

	public void setData(Object obj) {
		Map<String,Object> map = (Map<String,Object>)obj;
		newsLetterUrl = (String)map.get("url");
		getDC().getImageView().setImageBitmap(null);

		if(bitmap!=null && !bitmap.isRecycled()){
			bitmap.recycle();
		}
		bitmap = imageFileCache.getBigImage(newsLetterUrl);
		if(bitmap==null){
			//远程加载图片,并保存到sdcard中
			if(Constant.netIsOK){
				getDC().getNewsletterProgressBar().setVisibility(View.VISIBLE);
			}

			startLoadImage();
		}else{

			getDC().loadImage(bitmap);

		}

	}

	private void startLoadImage(){
		new Thread(){
			public void run(){
				byte[] data;
				try {
					data = getImage(newsLetterUrl);
					if(data!=null){
						BitmapFactory.Options opt = new BitmapFactory.Options();
						opt.inPreferredConfig = Bitmap.Config.RGB_565;
						opt.inPurgeable = true;
						opt.inInputShareable = true;
		                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,opt);// bitmap
		                imageFileCache.saveBmpToSd(bitmap, newsLetterUrl);
		                if(bitmap!=null && !bitmap.isRecycled()){
		                		bitmap.recycle();
		                }
		                mHandler.sendEmptyMessage(0);
		            }
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}.start();
	}
	public void onClicked(int id) {
		super.onClicked(id);
	}

	/**
     * Get image from newwork
     * @param path The path of image
     * @return byte[]
     * @throws Exception
     */
    public byte[] getImage(String path) throws Exception{
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10 * 1000);
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
            return readStream(inStream);
        }else{
        		getDC().getNewsletterProgressBar().setVisibility(View.INVISIBLE);
        		Toast.makeText(context, "网络超时,获取图片失败",Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    /**
     * Get data from stream
     * @param inStream
     * @return byte[]
     * @throws Exception
     */
    public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1){
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }
保存图片到sdcard中的方法如下:
	public void saveBmpToSd(Bitmap bm, String url) {
		if (bm == null) {
			//需要保存的是一个空值
			return;
		}
		//判断sdcard上的空间
		if (FREE_SD_SPACE_NEEDED_TO_CACHE >freeSpaceOnSd()) {
			//SD空间不足
			return;
		}
    		String filename =convertUrlToFileName(url);
    		String dir = getDirectory();

    		checkDir(dir);

    		File file = new File(dir +"/" + filename);
    		try {
    		    file.createNewFile();
    			OutputStream outStream = new FileOutputStream(file);
    			if(filename.indexOf("png")>-1){
    				bm.compress(Bitmap.CompressFormat.PNG, 50, outStream);
    			}
    			if(filename.indexOf("jpeg")>-1 || filename.indexOf("jpg")>-1){
    				bm.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
    			}

    			outStream.flush();
    			outStream.close();

    		} catch (FileNotFoundException e) {
    			Log.w("ImageFileCache","FileNotFoundException");
    		} catch (IOException e) {
    			Log.w("ImageFileCache","IOException");
    		}
    }

上面的50代表逼真度,越大,保存后的文件就越大。

从sdcard获取图片的方法:"
public Bitmap getBigImage(final String url) {
		final String path = getDirectory() + "/" + convertUrlToFileName(url);
		File file = new File(path);
		if (file.exists()) {
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inPreferredConfig = Bitmap.Config.RGB_565;
			opts.inPurgeable = true;
			opts.inInputShareable = true;
			Bitmap bmp=BitmapFactory.decodeFile(path,opts);
			if(bmp==null)
			{
				file.delete();
			}else
			{
				updateFileTime(path);
				return bmp;
			}
		}
		return null;
	}




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:426434次
    • 积分:4921
    • 等级:
    • 排名:第5977名
    • 原创:96篇
    • 转载:5篇
    • 译文:1篇
    • 评论:86条