編輯:關於 Android 程式設計
核心思想是通過 BitmapFactory.Options 來縮放圖片,關鍵用到了它的 inSampleSize 參數(采樣率)。
當 inSampleSize 為 1 時,采樣後圖片大小與原圖相同;
當 inSampleSize 為 2 時,采樣後圖片的寬和高都是原來的 1/2,也就是說像素點是原來的 1/4,佔的內存自然是原來的 1/4,以此類推;
當 inSampleSize 小於 1 時,效果等同於等於 1。
壓縮流程如下:
1. 把 BitmapFactory.Options 的 inJustDecodeBounds 設為 true(此時只解析圖片原始寬高,並不真正加載圖片)。
2. 從 Options 中取出原始寬高 outWidth、outHeight。
3. 根據需要設置合適的采樣率。
4. 把 inJustDecodeBounds 設回 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;
}
如此便完成了一張圖片的壓縮。BitmapFactory 還有其他 decode 方法,我們也可以照樣仿寫。
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);
}
接下來結合一個小 demo 走一遍完整流程,先把圖片壓縮類封裝起來:
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;
}
}
然後就能拿來用了。activity_main2.xml:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://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() {
//在主線程加載 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);
}
}
最後記得獲取網絡權限。
運行結果——壓縮前後的 bitmap 大小對比:


以上就是圖片壓縮的完整示例,希望對大家的學習有所幫助。
設計模式筆記(6):適配器模式,Android UI 架構的靈魂
適配器模式(Adapter Pattern)是開發中出現頻率最高的模式之一——ListView 和 RecyclerView 的 Adapter 就是最直觀的例子。 生活
Android 熱修復之 AndFix 使用教程
一、AndFix 簡介 AndFix 全稱 Android hot-fix,是阿里巴巴推出的 Android 熱修復框架,支持 Android 2.3 到 6.0 版本,
深入解析 Android 四大組件之 Activity
一、Activity 是什麼 Activity 是 Android 應用中負責用戶交互的核心組件,可以把它理解為應用程序的「界面單元」。每一個 Activity 都會創建
用 Ant 自動化打包 Android 多環境、多渠道 APK
打包為什麼總是這麼累 做 Android 開發的人大概都經歷過這種折磨:一個 App 要鋪到豌豆莢、華為應用市場、小米商店、360 手機助手……每個渠道都要在代碼裡寫死不