學習了下圖檔壓縮的實作方式,代碼很簡單,小馬就不多講了,直接上代碼:
package com.xiaoma.temp.android.demo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
/**
* @Title: AndroidTempDemoActivity.java
* @Package com.xiaoma.temp.android.demo
* @Description: 壓縮測試類
* @author XiaoMa
*/
public class CompressActivity extends Activity{
private Bitmap bmap;
private ImageView image1;
private ImageView image2;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init(){
image1 = (ImageView)findViewById(R.id.imageView1);
image2 = (ImageView)findViewById(R.id.imageView2);
Bitmap image2Bit = copressImage("/sdcard/notes.png");
saveCompressPic(image2Bit);
Drawable d = new BitmapDrawable(image2Bit);
image2.setBackgroundDrawable(d);
/**
* 如果大家要儲存圖檔的話傳回bmap就行了。儲存方法也寫下面了。
* 如果有要用到截剪圖檔的功能。請留言,小馬一起發.
* @param imgPath
*/
@SuppressWarnings("unused")
private Bitmap copressImage(String imgPath){
File picture = new File(imgPath);
Options bitmapFactoryOptions = new BitmapFactory.Options();
//下面這個設定是将圖檔邊界不可調節變為可調節
bitmapFactoryOptions.inJustDecodeBounds = true;
bitmapFactoryOptions.inSampleSize = 2;
int outWidth = bitmapFactoryOptions.outWidth;
int outHeight = bitmapFactoryOptions.outHeight;
bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(),
bitmapFactoryOptions);
float imagew = 150;
float imageh = 150;
int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight
/ imageh);
int xRatio = (int) Math
.ceil(bitmapFactoryOptions.outWidth / imagew);
if (yRatio > 1 || xRatio > 1) {
if (yRatio > xRatio) {
bitmapFactoryOptions.inSampleSize = yRatio;
} else {
bitmapFactoryOptions.inSampleSize = xRatio;
}
}
bitmapFactoryOptions.inJustDecodeBounds = false;
bitmapFactoryOptions);
if(bmap != null){
//ivwCouponImage.setImageBitmap(bmap);
return bmap;
}
return null;
}
* 儲存方法實作
* @param bitmap
private void saveCompressPic(Bitmap bitmap){
File file=new File("/sdcard/kkk/notes2.png");
if(!file.exists()){
file.mkdirs();
Log.i("KKK", "調用咯"+"..."+file.toString());
try {
FileOutputStream out=new FileOutputStream(file);
if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)){
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
}
源碼小馬也放附件裡面了,代碼臨時寫的,很簡單,有需要的下載下傳下,不需要的請直接跳過。。吼吼。。有問題請直接批評指點。。謝謝
<a href="http://down.51cto.com/data/2359942" target="_blank">附件:http://down.51cto.com/data/2359942</a>
本文轉自華華世界 51CTO部落格,原文連結:http://blog.51cto.com/mzh3344258/791522,如需轉載請自行聯系原作者