1、xml文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="51dp"
android:onClick="onClick"
android:text="縮略圖" />
<ImageView
android:id="@+id/show_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
2、製作縮略圖
package com.phone.day24_imagebitmap;
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
/**
* 製作圖片縮略圖
*
*
*
*/
public class MainActivity extends Activity {
ImageView show_tv;
Bitmap resourseImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show_tv = (ImageView) findViewById(R.id.show_iv);
// 將圖片從資源文件中拿出
resourseImage = BitmapFactory.decodeResource(getResources(),
R.drawable.image);
// 顯示當前資源圖片
show_tv.setImageBitmap(resourseImage);
}
public void onClick(View view) {
// TODU 製作縮略圖
// 將Bitmap 轉換爲數組
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
resourseImage.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
// 製作縮略圖
Bitmap map = getBitmap(outputStream.toByteArray(), 200, 100);
show_tv.setImageBitmap(map);
}
/**
* 製作縮略圖
*
*
* @param bytes
* 數組資源
* @param newWidth
* 新的寬度
* @param newheight
* 新的高度
* @return
*/
public Bitmap getBitmap(byte[] bytes, int newWidth, int newheight) {
// 可以來設置一些圖片的屬性參數
BitmapFactory.Options options = new BitmapFactory.Options();
// 緊解碼圖片邊緣 設置爲true 獲取寬高(節省內存) , 但是 decodeByteArray 方法的返回值爲null,
options.inJustDecodeBounds = true;
// 用options 屬性 解碼圖片邊緣
BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
// 獲取圖片寬高
int oldWidth = options.outWidth;
int oldHeight = options.outHeight;
// 計算新的比例
int scalWidth = oldWidth / newWidth;
int scalheight = oldHeight / newheight;
// 計算縮放比例
int scal = scalWidth > scalheight ? scalheight : scalWidth;
// 設置該方法 爲false 否則 decodeByteArray 將返回爲null
options.inJustDecodeBounds = false;
// 設置縮放比例
options.inSampleSize = scal;
// 轉換新圖片
Bitmap map = BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
options);
// 返回
return map;
}
}
完工!!!