androidbitmap压缩
① 请问在android 编程,Bitmap 怎么转换成 file
static boolean saveBitmap2file(Bitmap bmp,String filename){
CompressFormat format= Bitmap.CompressFormat.JPEG;
int quality = 100;
OutputStream stream = null;
try {
stream = new FileOutputStream("/sdcard/" + filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bmp.compress(format, quality, stream);
}
stream = new FileOutputStream("/sdcard/" + filename);
获取要保存到的文件的文件流
bmp.compress(format, quality, stream);
把指定的bitmp压缩到文件中 就是保存在指定文件中 format是文件格式(Bitmap.CompressFormat.JPEG jpeg) quality 是品质(100 就是原质量)
看名字 saveBitmap2file
你要上传的话 就去指定位置取这个file就行 路径的问题 可能有写真机找不到/sdcard/
建议 Environment类取地址 保存和读取时 都用Environment.getXXXX
② android bitmap 改变图片大小
Optionsoptions1=newOptions();
options1.inJustDecodeBounds=true;
BitmapFactory.decodeFile(filePath,options1);
options1.inSampleSize=RegisterTool.calculateInSampleSize(options1,110,160);//110,160:转换后的宽和高,具体值会有些出入
options1.inJustDecodeBounds=false;
Bitmapbitmap=BitmapFactory.decodeFile(filePath,options1);//filePath:文件路径
(BitmapFactory.Optionsoptions,
intreqWidth,intreqHeight){
finalintheight=options.outHeight;
finalintwidth=options.outWidth;
intinSampleSize=1;
if(height>reqHeight||width>reqWidth){
finalintheightRatio=Math.round((float)height
/(float)reqHeight);
finalintwidthRatio=Math.round((float)width/(float)reqWidth);
inSampleSize=heightRatio<widthRatio?widthRatio:heightRatio;
}
returninSampleSize;
}
//压缩图片并将Bitmap保存到本地
FileOutputStreamout=newFileOutputStream(newFile(filePath));
saveBitmap.compress(Bitmap.CompressFormat.JPEG,60,out);//60代表压缩40%
③ android bitmap怎么做缓存
Bitmap是Android系统中的图像处理的最重要类之一。用它可以获取图像文件信息,进行图像剪切、旋转、缩放等操作,并可以指定格式保存图像文件。
重要函数
public void recycle() // 回收位图占用的内存空间,把位图标记为Dead
public final boolean isRecycled() //判断位图内存是否已释放
public final int getWidth()//获取位图的宽度
public final int getHeight()//获取位图的高度
public final boolean isMutable()//图片是否可修改
public int getScaledWidth(Canvas canvas)//获取指定密度转换后的图像的宽度
public int getScaledHeight(Canvas canvas)//获取指定密度转换后的图像的高度
public boolean compress(CompressFormat format, int quality, OutputStream stream)//按指定的图片格式以及画质,将图片转换为输出流。
format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG
quality:画质,0-100.0表示最低画质压缩,100以最高画质压缩。对于PNG等无损格式的图片,会忽略此项设置。
public static Bitmap createBitmap(Bitmap src) //以src为原图生成不可变得新图像
public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)//以src为原图,创建新的图像,指定新图像的高宽以及是否可变。
public static Bitmap createBitmap(int width, int height, Config config)——创建指定格式、大小的位图
public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height)以source为原图,创建新的图片,指定起始坐标以及新图像的高宽。
BitmapFactory工厂类:
Option 参数类:
public boolean inJustDecodeBounds//如果设置为true,不获取图片,不分配内存,但会返回图片的高度宽度信息。
public int inSampleSize//图片缩放的倍数
public int outWidth//获取图片的宽度值
public int outHeight//获取图片的高度值
public int inDensity//用于位图的像素压缩比
public int inTargetDensity//用于目标位图的像素压缩比(要生成的位图)
public byte[] inTempStorage //创建临时文件,将图片存储
public boolean inScaled//设置为true时进行图片压缩,从inDensity到inTargetDensity
public boolean inDither //如果为true,解码器尝试抖动解码
public Bitmap.Config inPreferredConfig //设置解码器
public String outMimeType //设置解码图像
public boolean inPurgeable//当存储Pixel的内存空间在系统内存不足时是否可以被回收
public boolean inInputShareable //inPurgeable为true情况下才生效,是否可以共享一个InputStream
public boolean inPreferQualityOverSpeed //为true则优先保证Bitmap质量其次是解码速度
public boolean inMutable //配置Bitmap是否可以更改,比如:在Bitmap上隔几个像素加一条线段
public int inScreenDensity //当前屏幕的像素密度
工厂方法:
public static Bitmap decodeFile(String pathName, Options opts) //从文件读取图片
public static Bitmap decodeFile(String pathName)
public static Bitmap decodeStream(InputStream is) //从输入流读取图片
public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts)
public static Bitmap decodeResource(Resources res, int id) //从资源文件读取图片
public static Bitmap decodeResource(Resources res, int id, Options opts)
public static Bitmap decodeByteArray(byte[] data, int offset, int length) //从数组读取图片
public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts)
public static Bitmap decodeFileDescriptor(FileDescriptor fd)//从文件读取文件 与decodeFile不同的是这个直接调用JNI函数进行读取 效率比较高
public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts)
Bitmap.Config inPreferredConfig :
枚举变量 (位图位数越高代表其可以存储的颜色信息越多,图像越逼真,占用内存越大)
public static final Bitmap.Config ALPHA_8 //代表8位Alpha位图 每个像素占用1byte内存
public static final Bitmap.Config ARGB_4444 //代表16位ARGB位图 每个像素占用2byte内存
public static final Bitmap.Config ARGB_8888 //代表32位ARGB位图 每个像素占用4byte内存
public static final Bitmap.Config RGB_565 //代表8位RGB位图 每个像素占用2byte内存
Android中一张图片(BitMap)占用的内存主要和以下几个因数有关:图片长度,图片宽度,单位像素占用的字节数。一张图片(BitMap)占用的内存=图片长度*图片宽度*单位像素占用的字节数
④ 在android开发中加载的图片太大,有好几十兆,应该怎么办
如果图片太大会造成OOM内存溢出的错误,需要用Bitmap的压缩机制。
解决方案:
1.使用BitmapFactory.decodeStream替代createBitmap方法
原因是该方法直读取图片字节,调用JNI>>nativeDecodeAsset()来完成decode,无需再使用java层的createBitmap。
2.使用压缩读取技术
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageSdUri, options);
final int height = options.outHeight;
final int width = options.outWidth;
options.inSampleSize = 1;
int w = 320;
int h = 480;
h = w*height/width;//计算出宽高等比率
int a = options.outWidth/ w;
int b = options.outHeight / h;
options.inSampleSize = Math.max(a, b);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(imageSdUri, options);
3.及时释放Bitamp
Bitmap对象在不使用时,我们应该先调用recycle()释放内存,然后才它设置为null.虽然recycle()从源码上看,调用它应该能立即释放Bitmap的主要内存,但是测试结果显示它并没能立即释放内存。但是我它应该还是能大大的加速Bitmap的主要内存的释放。
⑤ android 图片质量压缩和尺寸压缩有什么区别
这个方法用来将特定格式的压缩图片写入输出流(OutputStream)中,当然例如输出流与文件联系在一起,压缩后的图片也就是一个文件。如果压缩成功则返回true,其中有三个参数:
format是压缩后的图片的格式,可取值:Bitmap.CompressFormat .JPEG、~.PNG、~.WEBP。
quality的取值范围为[0,100],值越小,经过压缩后图片失真越严重,当然图片文件也会越小。(PNG格式的图片会忽略这个值的设定)
stream指定压缩的图片输出的地方,比如某文件。
上述方法还有一个值得注意的地方是:当用BitmapFactory decode文件时可能返回一个跟原图片不同位深的图片,或者丢失了每个像素的透明值(alpha),比如说,JPEG格式的图片仅仅支持不透明的像素。文章android图片压缩在文末提到的下面这点可能就是这个原因:
当调用bitmap.compress(CompressFormat.JPEG, 100, fos);保存为图片时发现图片背景为黑色,如下图:
下面是质量压缩的代码:
(Bitmapbmp,Filefile){
ByteArrayOutputStreambaos=newByteArrayOutputStream();
intoptions=80;//个人喜欢从80开始,
bmp.compress(Bitmap.CompressFormat.JPEG,options,baos);
while(baos.toByteArray().length/1024>100){
baos.reset();
options-=10;
bmp.compress(Bitmap.CompressFormat.JPEG,options,baos);
}
try{
FileOutputStreamfos=newFileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
}catch(Exceptione){
e.printStackTrace();
}
}
这段代码来自Android图片压缩总结,我根据自己的需求改了改,但是大同小异,所以就直接贴了。
随着代码中的option逐渐变小,我们可以在logcat中打印baos的大小来查看图片的大小。我们也可以去掉while的循环条件,一直压缩下去看效果,最终一张照片可能就由原来的3、4M变成了几百K甚至几百B了。我在试的过程中将option设置成100,压缩后偶尔会出现一张3、4M的图片经过压缩后竟变成了6、7M,这里还是有点困惑,不知道为什么。
随后,我想把这个压缩后的图片(1、200KB)填充到ImageView中时却失败了,logcat中提示图片过大!这就是文章开头提到的问题,虽然我们通过质量压缩使File形式的图片文件缩小了,但是并没有改变图片的宽高,原先是1080*1920分辨率的图片经压缩后还是1080*1920,而File格式转换成Bitmap格式进入到内存中时,内存是根据图片的像素数量来给图片分配内存大小的,还是有好几M,因此填充ImageView失败。
顺便提一下,可以用bitmap.getByteCount()获取存储bitmap像素的内存大小,但是KITKAT(Android 4.4版本)以后用getAllocateByteCount()获取。一般情况下,后者返回值比前者大,比如,当bitmap被重用去decode另外更小的bitmaps时,或者被人为地配置一下属性值,比如setWidth()、setHeight()、reconfigure()时,如果bitmap不做以上操作,二者的返回值应该是一样的。(译文,不太懂)
二、尺寸压缩
特点: 通过设置采样率, 减少图片的像素, 达到对内存中的Bitmap进行压缩
我们主要通过BitmapFactory中的decodeFile方法对图片进行尺寸压缩:
publicstaticBitmapdecodeFile(StringpathName,BitmapFactory.Optionsopts)
public static Bitmap decodeFile (String pathName, BitmapFactory.Options opts)
其中有两个参数:
pathName是图片文件的路径。
opts 就是所谓的采样率,它里边有很多属性可以设置,我们通过设置属性来达到根据自己的需要,压缩出指定的图片。其中比较常用的属性有:
booleaninJustDecodeBounds—— 如果设置为true,则只读取bitmap的宽高,而忽略内容。
intinSampleSize—— 如果>1,调用decodeFile方法后,就会得到一个更小的bitmap对象(已压缩)。比如设置为2,那么新Bitmap的宽高都会是原Bitmap宽高的1/2,总体大小自然就是原来的1/4了,以此类推。
booleaninPurgeable—— 如果设置为true,压缩后的图片像素占的内存将会在系统清理内存的时候被回收掉,当像素的信息再次被用到时将会自动重新decode该像素(比如getPixels()时)。(慎用!重复decode可以会造成UI的卡顿,API level 21 已弃用)
booleaninInputShareable—— 与inPurgeable配合使用,如果inPurgeable设置成false,自动忽略此值,如果inPurgeable为true,此值决定是否该bitmap能分享引用给输入数据(inputstream,array等),或者必须进行深拷贝。API level 21 已弃用。(这是译文,不太理解!!!)
下面是一段实现的代码
privateBitmapsizeCompres(Stringpath,intrqsW,intrqsH){
//用option设置返回的bitmap对象的一些属性参数
finalBitmapFactory.Optionsoptions=newBitmapFactory.Options();
options.inJustDecodeBounds=true;//设置仅读取Bitmap的宽高而不读取内容
BitmapFactory.decodeFile(path,options);//获取到图片的宽高,放在option里边
finalintheight=options.outHeight;//图片的高度放在option里的outHeight属性中
finalintwidth=options.outWidth;
intinSampleSize=1;
if(rqsW==0||rqsH==0){
options.inSampleSize=1;
}elseif(height>rqsH||width>rqsW){
finalintheightRatio=Math.round((float)height/(float)rqsH);
finalintwidthRatio=Math.round((float)width/(float)rqsW);
inSampleSize=heightRatio<widthRatio?heightRatio:widthRatio;
options.inSampleSize=inSampleSize;
}
returnBitmapFactory.decodeFile(path,options);//主要通过option里的inSampleSize对原图片进行按比例压缩
}
private Bitmap sizeCompres(String path, int rqsW, int rqsH) {
// 用option设置返回的bitmap对象的一些属性参数
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;// 设置仅读取Bitmap的宽高而不读取内容
BitmapFactory.decodeFile(path, options);// 获取到图片的宽高,放在option里边
final int height = options.outHeight;//图片的高度放在option里的outHeight属性中
final int width = options.outWidth;
int inSampleSize = 1;
if (rqsW == 0 || rqsH == 0) {
options.inSampleSize = 1;
} else if (height > rqsH || width > rqsW) {
final int heightRatio = Math.round((float) height / (float) rqsH);
final int widthRatio = Math.round((float) width / (float) rqsW);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
options.inSampleSize = inSampleSize;
}
return BitmapFactory.decodeFile(path, options);// 主要通过option里的inSampleSize对原图片进行按比例压缩
}
上面就是简单的质量压缩与尺寸压缩。
⑥ android 图片压缩50*1024是多少
总结来看,图片有三种存在形式:硬盘上时是file,网络传输时是stream,内存中是stream或bitmap。
所谓的质量压缩,它其实只能实现对file的影响,你可以把一个file转成bitmap再转成file,或者直接将一个bitmap转成file时,这个最终的file是被压缩过的,但是中间的bitmap并没有被压缩(或者说几乎没有被压缩,我不确定),因为bigmap在内存中的大小是按像素计算的,也就是width * height,对于质量压缩,并不会改变图片的像素,所以就算质量被压缩了,但是bitmap在内存的占有率还是没变小,但你做成file时,它确实变小了;
而尺寸压缩由于是减小了图片的像素,所以它直接对bitmap产生了影响,当然最终的file也是相对的变小了;
最后把自己总结的工具类贴出来:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import <strong style="color:black;background-color:#ffff66">android</strong>.graphics.Bitmap;
import <strong style="color:black;background-color:#ffff66">android</strong>.graphics.Bitmap.Config;
import <strong style="color:black;background-color:#ffff66">android</strong>.graphics.BitmapFactory;
⑦ android 怎么将bitmap进行尺寸压缩
总结来看,图片有三种存在形式:硬盘上时是file,网络传输时是stream,内存中是stream或bitmap,所谓的质量压缩,它其实只能实现对file的影响,你可以把一个file转成bitmap再转成file,或者直接将一个bitmap转成file时,这个最终的file是被压缩过的,但是中间的bitmap并没有被压缩(或者说几乎没有被压缩,我不确定),因为bigmap在内存中的大小是按像素计算的,也就是width * height,对于质量压缩,并不会改变图片的像素,所以就算质量被压缩了,但是bitmap在内存的占有率还是没变小,但你做成file时,它确实变小了;
而尺寸压缩由于是减小了图片的像素,所以它直接对bitmap产生了影响,当然最终的file也是相对的变小了;
最后把自己总结的工具类贴出来:
[java] view plain
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
⑧ 调用安卓系统自带的照相机,发现拍完照返回的bitmap是被压缩过的,想问下是不是每个安卓系统都是这样
拍完照后,检索数据库的时候读取其地址,不要转换成bitmap。用文件方式读取。
⑨ android bitmapfactory.options怎么把突变压缩成固定的像素
设置缩放大小对图片作处理
[java] view plain
public Bitmap getBitmapFromFile(File dst, int width, int height) {
if (null != dst && dst.exists()) {
BitmapFactory.Options opts = null;
if (width > 0 && height > 0) {
opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(dst.getPath(), opts);
// 计算图片缩放比例
final int minSideLength = Math.min(width, height);
opts.inSampleSize = computeSampleSize(opts, minSideLength,
width * height);
opts.inJustDecodeBounds = false;
opts.inInputShareable = true;
opts.inPurgeable = true;
}
try {
return BitmapFactory.decodeFile(dst.getPath(), opts);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
}
return null;
}
public static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math
.floor(w / minSideLength), Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
[java] view plain
/**
* 获取经过处理的资源图,包括普通图和.9图
* @param context 应用环境
* @param id 资源id
* @return Drawable格式的资源
* <p>
* 以1080p为基准,小于此尺寸的缩写,大于此尺寸的放大
*/
public static Drawable getCompatibleDrawable(Context context, int id) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDensity = 240;
options.inScreenDensity = (int) (240*ratio);
options.inTargetDensity = (int) (240*ratio);
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
id, options);
byte[] ninePathChunk = bitmap.getNinePatchChunk();
if (NinePatch.isNinePatchChunk(ninePathChunk)) {
NinePatch ninePath = new NinePatch(bitmap, ninePathChunk, null);
return new NinePatchDrawable(ninePath);
} else {
return new BitmapDrawable(bitmap);
}
}