Bitmap之compress图片压缩
生活随笔
收集整理的這篇文章主要介紹了
Bitmap之compress图片压缩
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package com.loaderman.customviewdemo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView iv_1 = (ImageView) findViewById(R.id.img1);
ImageView iv_2 = (ImageView) findViewById(R.id.img2);
Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.cat);
iv_1.setImageBitmap(bmp);
//壓縮圖像后,顯示
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 1, bos);
byte[] bytes = bos.toByteArray();
Bitmap bmp1 = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
iv_2.setImageBitmap(bmp1);
ImageView iv_3 = (ImageView) findViewById(R.id.img3);
ImageView iv_4 = (ImageView) findViewById(R.id.img4);
ByteArrayOutputStream bos3 = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 1, bos3);
byte[] bytes3 = bos3.toByteArray();
Bitmap bmp3 = BitmapFactory.decodeByteArray(bytes3, 0, bytes3.length);
iv_3.setImageBitmap(bmp3);
ByteArrayOutputStream bos4 = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.WEBP, 1, bos4);
byte[] bytes4 = bos4.toByteArray();
Bitmap bmp4 = BitmapFactory.decodeByteArray(bytes4, 0, bytes4.length);
iv_4.setImageBitmap(bmp4);
}
/**
* 保存文件到手機SD卡根目錄中
* @param bitmap
*/
private void saveBmp(Bitmap bitmap) {
File fileDir = Environment.getExternalStorageDirectory();
String path = fileDir.getAbsolutePath() + "/lavor.webp";
File file = new File(path);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.WEBP, 10, outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
效果:
總結
以上是生活随笔為你收集整理的Bitmap之compress图片压缩的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据的分析----分析检验
- 下一篇: maven-assembly-plugi