国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > Android > 正文

Android實(shí)現(xiàn)圖片壓縮示例代碼

2019-12-12 03:59:42
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

核心思想是通過(guò)BitmapFactory.Options來(lái)縮放圖片,主要是用到了它的inSampleSize參數(shù)(采樣率)

當(dāng)inSampleSize為1的時(shí)候,采樣后的圖片大小為圖片的原始大小;

當(dāng)inSampleSize為2的時(shí)候,采樣后的圖片的寬和高是原來(lái)的1/2,也就是說(shuō),它的像素點(diǎn)是原來(lái)的1/4,占的內(nèi)存自然就是原來(lái)的1/4了。以此類(lèi)推。

當(dāng)inSampleSize小于1的時(shí)候,效果和等于1的時(shí)候是一樣的。

壓縮流程如下:

1.BitmapFactory.Options 的inJustDecodeBounds參數(shù)設(shè)置為true(這個(gè)時(shí)候BitmapFactory只是解析圖片的原始寬高,并不會(huì)去加載圖片)。

2.從BitmapFactory.Options 中取出圖片的原始寬高,outWidth,outHeight。

3.根據(jù)自己的需要設(shè)置合適的采樣率。

4.BitmapFactory.Options 的inJustDecodeBounds參數(shù)設(shè)置為false,然后就可以加載圖片了。

下面我們看代碼:

public Bitmap decodeSampledBitmapFromBytes(byte[] bytes,int reqWidth,int reqHeight){    final BitmapFactory.Options options = new BitmapFactory.Options();    options.inJustDecodeBounds = true;    BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);    options.inJustDecodeBounds = false;    return BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);  }public int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight){    if(reqWidth == 0 || reqHeight == 0){      return 1;    }    final int width = options.outWidth;    final int height = options.outHeight;    int inSampleSize = 1;    if( width > reqWidth || height > reqHeight){      final int halfWidth = width / 2;      final int halfHeight = height / 2;      while ((halfWidth / inSampleSize) >= reqWidth && (halfHeight / inSampleSize) >= reqHeight){        inSampleSize *=2;      }    }    return inSampleSize;  }

如此一來(lái),就完成了一張圖片的壓縮。另外,BitmapFactory還有其它的decode方法,我們也可以仿照上面的來(lái)寫(xiě)。

public Bitmap decodeSampledBitmapFromResource(Resources res,int resId,int reqWidth,int reqHeight){    final BitmapFactory.Options options = new BitmapFactory.Options();    options.inJustDecodeBounds = true;    BitmapFactory.decodeResource(res,resId,options);    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);    options.inJustDecodeBounds = false;    return BitmapFactory.decodeResource(res,resId,options);  }
public Bitmap decodeSampledBitmapFromDescrptor(FileDescriptor fd,int reqWidth,int reqHeight){    final BitmapFactory.Options options = new BitmapFactory.Options();    options.inJustDecodeBounds = true;    BitmapFactory.decodeFileDescriptor(fd,null,options);    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);    options.inJustDecodeBounds = false;    return BitmapFactory.decodeFileDescriptor(fd,null,options);  }

接下來(lái)結(jié)合一個(gè)小demo來(lái)實(shí)現(xiàn)一個(gè)完整的流程

先把圖片壓縮類(lèi)封裝起來(lái)

public class ImageResizer {  private static final String TAG = "ImageResizer";  public ImageResizer(){}  public Bitmap decodeSampledBitmapFromResource(Resources res,int resId,int reqWidth,int reqHeight){    final BitmapFactory.Options options = new BitmapFactory.Options();    options.inJustDecodeBounds = true;    BitmapFactory.decodeResource(res,resId,options);    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);    options.inJustDecodeBounds = false;    return BitmapFactory.decodeResource(res,resId,options);  }  public Bitmap decodeSampledBitmapFromBytes(byte[] bytes,int reqWidth,int reqHeight){    final BitmapFactory.Options options = new BitmapFactory.Options();    Bitmap a = BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);    Log.d(TAG, "before bitmap : " + a.getRowBytes() * a.getHeight());    options.inJustDecodeBounds = true;    BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);    options.inJustDecodeBounds = false;    Bitmap b = BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);    Log.d(TAG, "after bitmap : " + b.getRowBytes() * b.getHeight());    return b;  }  public Bitmap decodeSampledBitmapFromDescrptor(FileDescriptor fd,int reqWidth,int reqHeight){    final BitmapFactory.Options options = new BitmapFactory.Options();    options.inJustDecodeBounds = true;    BitmapFactory.decodeFileDescriptor(fd,null,options);    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);    options.inJustDecodeBounds = false;    return BitmapFactory.decodeFileDescriptor(fd,null,options);  }  public int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight){    if(reqWidth == 0 || reqHeight == 0){      return 1;    }    final int width = options.outWidth;    final int height = options.outHeight;    int inSampleSize = 1;    if( width > reqWidth || height > reqHeight){      final int halfWidth = width / 2;      final int halfHeight = height / 2;      while ((halfWidth / inSampleSize) >= reqWidth && (halfHeight / inSampleSize) >= reqHeight){        inSampleSize *=2;      }    }    return inSampleSize;  }}

然后就可以拿來(lái)用了:

activity_main2.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools"  android:id="@+id/activity_main2"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:paddingBottom="@dimen/activity_vertical_margin"  android:paddingLeft="@dimen/activity_horizontal_margin"  android:paddingRight="@dimen/activity_horizontal_margin"  android:paddingTop="@dimen/activity_vertical_margin"  tools:context="com.example.yuan.test.Main2Activity">  <ImageView    android:id="@+id/main2Iv"    android:layout_width="200dp"    android:layout_height="200dp" /></RelativeLayout>

Main2Activity.Java

public class Main2Activity extends AppCompatActivity {  private ImageView iv;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main2);    initView();    testHttp(iv);  }  private void testHttp(final ImageView iv) {    new Thread(new Runnable() {      @Override      public void run() {        String urlString = "https://static.pexels.com/photos/295818/pexels-photo-295818.jpeg";        HttpURLConnection urlConnection = null;        InputStream in = null;        ByteArrayOutputStream outStream = null;        try {          URL url = new URL(urlString);          urlConnection = (HttpURLConnection) url.openConnection();          in = urlConnection.getInputStream();          byte[] buffer = new byte[1024];          int len;          outStream = new ByteArrayOutputStream();          while ((len = in.read(buffer)) != -1){            outStream.write(buffer,0,len);          }          final byte[] data = outStream.toByteArray();          runOnUiThread(new Runnable() {            @Override            public void run() { //在主線(xiàn)程加載UI              iv.setImageBitmap(new ImageResizer().decodeSampledBitmapFromBytes(data,200,200));            }          });        } catch (IOException e) {          e.printStackTrace();        }finally {          try {            if(urlConnection !=null){              urlConnection.disconnect();            }            if(in != null){              in.close();            }            if(outStream != null){              outStream.close();            }          } catch (IOException e) {            e.printStackTrace();          }        }      }    }).start();  }  private void initView() {    iv = (ImageView) findViewById(R.id.main2Iv);  }}

最后記得獲取網(wǎng)絡(luò)權(quán)限

運(yùn)行的結(jié)果:

壓縮前后的bitmap大小對(duì)比

壓縮前后的bitmap大小對(duì)比

壓縮前后的bitmap大小對(duì)比

這里寫(xiě)圖片描述 

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 石狮市| 新郑市| 鸡西市| 华阴市| 阳新县| 奉新县| 临武县| 肃宁县| 保康县| 墨竹工卡县| 周口市| 贺州市| 大理市| 榕江县| 宽城| 安西县| 富蕴县| 永善县| 鹤壁市| 上高县| 阳城县| 五华县| 虎林市| 冕宁县| 普陀区| 太原市| 连城县| 普定县| 龙岩市| 荃湾区| 绍兴市| 法库县| 汪清县| 偏关县| 陇川县| 竹山县| 巴南区| 耿马| 榆社县| 阿拉善右旗| 龙山县|