在读取图片的时候压缩减小内存开支

来源:互联网 发布:淘宝宝贝数据包下载 编辑:程序博客网 时间:2024/04/28 23:31

这个问题真是把我折腾的够呛:

package com.example.tupian;import java.io.IOException;import java.io.InputStream;import java.net.URL;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.annotation.SuppressLint;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.drawable.Drawable;import android.util.Log;import android.view.Menu;import android.widget.ImageView;import android.widget.Toast;@SuppressLint("NewApi")public class MainActivity extends Activity {private static Bitmap bitm;private static Bitmap bitm2;private ImageView iv;private ImageView iv2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); iv = (ImageView)findViewById(R.id.iv); iv2 = (ImageView)findViewById(R.id.iv2); Thread t = new Thread(new imgThred()); t.start();}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}class imgThred implements Runnable{ public void run(){//dd= getDrawable("http://smartcost.com.cn/global/upload/img/20140520/1400549692206.jpg"); try {bitm = revitionImageSize("http://smartcost.com.cn/global/upload/img/20140520/1400549692206.jpg",300);bitm2 = revitionImageSize("http://smartcost.com.cn/global/upload/img/20140520/1400549692206.jpg",150); } catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}msHandl.sendMessage(new Message());}}Handler msHandl = new Handler(){@Overridepublic void handleMessage(Message msg) {iv.setImageBitmap(bitm);iv2.setImageBitmap(bitm2);}};private Bitmap revitionImageSize(String path, int size) throws IOException { URL url;  url = new URL(path);  // 取得图片 InputStream temp = url.openStream(); BitmapFactory.Options options = new BitmapFactory.Options(); // 这个参数代表,不为bitmap分配内存空间,只记录一些该图片的信息(例如图片大小),说白了就是为了内存优化 options.inJustDecodeBounds = true; // 通过创建图片的方式,取得options的内容(这里就是利用了java的地址传递来赋值) BitmapFactory.decodeStream(temp, null, options); // 关闭流 temp.close(); // 生成压缩的图片 int i = 0; Bitmap bitmap = null; while (true) { // 这一步是根据要设置的大小,使宽和高都能满足 if ((options.outWidth >> i <= size) && (options.outHeight >> i <= size)) { // 重新取得流,注意:这里一定要再次加载,不能二次使用之前的流! temp = url.openStream(); // 这个参数表示 新生成的图片为原始图片的几分之一。 options.inSampleSize = (int) Math.pow(2.0D, i); // 这里之前设置为了true,所以要改为false,否则就创建不出图片 options.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeStream(temp, null, options); break; } i += 1; } double bitcount =bitmap.getByteCount()/1000;Log.e("bitcount", bitcount+"");return bitmap;}}

2、从资源中获取Bitmap
Resources res=getResources();

Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);


另外附上bitmap和SD卡的操作哦:http://blog.sina.com.cn/s/blog_a72ec20c01015rwj.html

唉,虽然今天晚上弄到现在,但明天到公司又是一场恶战。。。

1 0
原创粉丝点击