图片压缩

本文介绍了一种使用Android平台下的BitmapFactory进行图片压缩的方法。通过设置BitmapFactory.Options参数,可以有效地控制图片的尺寸,并将压缩后的图片保存到SD卡中。此外,还提供了从SD卡读取图片并将其转换为字节数组的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. //对图片进行压缩
  2. BitmapFactory.Optionsoptions=newBitmapFactory.Options();
  3. options.inJustDecodeBounds=true;
  4. //获取这个图片的宽和高
  5. Bitmapbitmap=BitmapFactory.decodeFile("/sdcard/dcim/Camera/hello.jpg",options);//此时返回bm为空
  6. options.inJustDecodeBounds=false;
  7. //计算缩放比
  8. intbe=(int)(options.outHeight/(float)200);
  9. if(be<=0)
  10. be=1;
  11. options.inSampleSize=be;
  12. //重新读入图片,注意这次要把options.inJustDecodeBounds设为false哦
  13. bitmap=BitmapFactory.decodeFile("/sdcard/dcim/Camera/hello.jpg",options);
  14. intw=bitmap.getWidth();
  15. inth=bitmap.getHeight();
  16. System.out.println(w+""+h);
  17. myImageView.setImageBitmap(bitmap);
  18. //保存入sdCard
  19. Filefile2=newFile("/sdcard/dcim/Camera/test.jpg");
  20. try{
  21. FileOutputStreamout=newFileOutputStream(file2);
  22. if(bitmap.compress(Bitmap.CompressFormat.JPEG,100,out)){
  23. out.flush();
  24. out.close();
  25. }
  26. }catch(Exceptione){
  27. //TODO:handleexception
  28. }
  29. //读取sd卡
  30. Filefile=newFile("/sdcard/dcim/Camera/test.jpg");
  31. intmaxBufferSize=16*1024;
  32. intlen=0;
  33. ByteArrayOutputStreamoutStream=newByteArrayOutputStream();
  34. BufferedInputStreambufferedInputStream;
  35. try{
  36. bufferedInputStream=newBufferedInputStream(newFileInputStream(file));
  37. intbytesAvailable=bufferedInputStream.available();
  38. intbufferSize=Math.min(bytesAvailable,maxBufferSize);
  39. byte[]buffer=newbyte[bufferSize];
  40. while((len=bufferedInputStream.read(buffer))!=-1)
  41. {
  42. outStream.write(buffer,0,bufferSize);
  43. }
  44. data=outStream.toByteArray();
  45. outStream.close();
  46. bufferedInputStream.close();
  47. }catch(FileNotFoundExceptione){
  48. e.printStackTrace();
  49. }catch(IOExceptione){
  50. e.printStackTrace();
  51. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值