android图片压缩源代码
我在写一个图片压缩的方法,因为要上传到服务器,所以图片不可以过大。
网上的这些方法也都烂了,可是都不怎么管用。比如我现在使用的。
我在这个循环里设置了,如果baos.toByteArray().length / 1024>50成立,就继续压缩。
可是我设置段点之后,发现baos.toByteArray().length / 1024已经运行到小于50了,然后返回这个bitmap。当我上传到服务器的时候,图片竟然是二三百K,我想问问大家有没有懂的,帮我一下。
或者哪位朋友有好的图片压缩方法给我一个。毕业论文
Java code? ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos); int options = 100; while ( baos.toByteArray().length / 1024>50) { baos.reset(); options -= 10; image.compress(Bitmap.CompressFormat.JPEG, options, baos); } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null); return bitmap;
我不需要图片宽高的那种压缩,我只想要一张图片在不让它失真太严重的情况下,能压缩到50k以下。实在不行100k以内也可以。但是不要失真太严重
首先 isBm 判断一下这个有多大?
package com.example.bitmapcompresstest;
import java.io.ByteArrayOutputStream;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getResources().getDrawable(R.drawable.koala123);
// BitmapFactory.Options opts =
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.koala123);
double maxSize =100.00;//限制的文件大小
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
//将字节换成KB
double mid = b.length/1024;
//判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
if (mid > maxSize) {
//获取bitmap大小 是允许最大大小的多少倍
double i = mid / maxSize;
//开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍 (1.保持刻度和高度和原bitmap比率一致,压缩后也达到了最大大小占用空间的大小)
bmp = zoomImage(bmp, bmp.getWidth() / Math.abs(i),
bmp.getHeight() / Math.abs(i));
}
ImageView imgView = (ImageView)findViewById(R.id.img);
imgView.setImageBitmap(bmp);
// Toast.makeText(this, "getRowBytes"+bmp.getRowBytes(), 0).show();
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos2);
byte[] b2 = baos2.toByteArray();
Toast.makeText(this, ""+b2.length/1024, 0).show();
}
public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
double newHeight) {
// 获取这个图片的宽和高
float width = bgimage.getWidth();
float height = bgimage.getHeight();
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算宽高缩放率
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
(int) height, matrix, true);
return bitmap;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}}