Android 图片压缩,Bitmap旋转,bitmap与byte[]之间相互转换,Bitmap与String互转

 频繁setImageBitmap引起oom问题解决方法

Glide.with(gsewmimg).load(getCodeBitmap(response.data.skip, R.mipmap.zhifuicon)).into(gsewmimg);

压缩前后。图片大小  2.22MB——>200KB

         

 1、图片压缩方法:


Bitmap bitmap;
byte[] buff;
buff = Bitmap2Bytes(bitmap);
BitmapFactory.Options ontain = new BitmapFactory.Options();
ontain.inSampleSize = 7;//值1为原图。值越大,压缩图片越小1-20
bitmap = BitmapFactory.decodeByteArray(buff, 0, buff.length, ontain);

压缩方法2:

int height = (int) ( mybitmap.getHeight() * (512.0 / mybitmap.getWidth()) );
mybitmap = Bitmap.createScaledBitmap(mybitmap, 512, height, true);


2、bitmap转byte


private byte[] Bitmap2Bytes(Bitmap bm) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    return baos.toByteArray();
}

3、byte转bitmap


private Bitmap Bytes2Bimap(byte[] b) {
    if (b.length != 0) {
        return BitmapFactory.decodeByteArray(b, 0, b.length);
    } else {
        return null;
    }
}

方法二,bitmap 转byte

              Bitmap frame = mCamera != null ? mCamera.Snapshot(mSelectedChannel) : null;frame = rotate(frame, 90);byte[] snapshot = getByteArrayFromBitmap(frame);if (snapshot!=null){String imageString = new String(Base64.encode(snapshot,Base64.DEFAULT));
//                LgqLogPlus.e("获取到imgstring保存了===== "+imageString);SharedPreUtil.putString(mDevUID,imageString);}

public static byte[] getByteArrayFromBitmap(Bitmap bitmap) {if (bitmap != null && !bitmap.isRecycled()) {ByteArrayOutputStream bos = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);return bos.toByteArray();} else {return null;}
}

byte转bitmap 

        String imgstring = SharedPreUtil.getString(this,mDevUID);
//       LgqLogPlus.e("获取到imgstring==== "+imgstring);if (imgstring!=null){byte[] bytsSnapshot = Base64.decode(imgstring.getBytes(), Base64.DEFAULT);Bitmap snapshot = (bytsSnapshot != null && bytsSnapshot.length > 0) ? getBitmapFromByteArray(bytsSnapshot) : null;bgimg.setImageBitmap(snapshot);}

public static Bitmap getBitmapFromByteArray(byte[] byts) {InputStream is = new ByteArrayInputStream(byts);return BitmapFactory.decodeStream(is, null, getBitmapOptions(2));
}public static BitmapFactory.Options getBitmapOptions(int scale) {BitmapFactory.Options options = new BitmapFactory.Options();options.inPurgeable = true;options.inInputShareable = true;options.inSampleSize = scale;try {BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options, true);} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchFieldException e) {// TODO Auto-generated catch blocke.printStackTrace();}return options;
}

旋转方法:

//Rotate Bitmap
public final static Bitmap rotate(Bitmap b, float degrees) {if (degrees != 0 && b != null) {Matrix m = new Matrix();m.setRotate(degrees, (float) b.getWidth() / 2,(float) b.getHeight() / 2);Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),b.getHeight(), m, true);if (b != b2) {b.recycle();b = b2;}}return b;
}

调用

bitmap = rotate(bitmap,90);

效果

选图

                    

Android报错:Throwing OutOfMemoryError failed to allocate a 42793710 byte allocation with 52488 free by

在<application>里加上android:hardwareAccelerated="false" 和 android:largeHeap="true"成功解决

 Bitmap与String互转

Bitmap frame = BitmapFactory.decodeResource(getResources(),R.mipmap.iv_charge2 );byte[] snapshot = getByteArrayFromBitmap(frame);if (snapshot!=null){String imageString = new String(Base64.encode(snapshot,Base64.DEFAULT));if (imageString!=null){byte[] bytsSnapshot = Base64.decode(imageString.getBytes(), Base64.DEFAULT);Bitmap snapshot2 = (bytsSnapshot != null && bytsSnapshot.length > 0) ? getBitmapFromByteArray(bytsSnapshot) : null;imageView.setImageBitmap(snapshot2);}
}

工具: 

public static byte[] getByteArrayFromBitmap(Bitmap bitmap) {if (bitmap != null && !bitmap.isRecycled()) {ByteArrayOutputStream bos = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);return bos.toByteArray();} else {return null;}
}public static Bitmap getBitmapFromByteArray(byte[] byts) {InputStream is = new ByteArrayInputStream(byts);return BitmapFactory.decodeStream(is, null, getBitmapOptions(2));
}public static BitmapFactory.Options getBitmapOptions(int scale) {BitmapFactory.Options options = new BitmapFactory.Options();options.inPurgeable = true;options.inInputShareable = true;options.inSampleSize = scale;try {BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options, true);} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchFieldException e) {// TODO Auto-generated catch blocke.printStackTrace();}return options;
}

private static void readBitmapScale(Context context, Uri uri, BitmapFactory.Options options) {if (uri == null) {return;}String scheme = uri.getScheme();if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||ContentResolver.SCHEME_FILE.equals(scheme)) {InputStream stream = null;try {stream = context.getContentResolver().openInputStream(uri);BitmapFactory.decodeStream(stream, null, options);} catch (Exception e) {Log.w("readBitmapScale", "Unable to open content: " + uri, e);} finally {if (stream != null) {try {stream.close();} catch (IOException e) {Log.e("readBitmapScale", "Unable to close content: " + uri, e);}}}} else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {Log.e("readBitmapScale", "Unable to close content: " + uri);} else {Log.e("readBitmapScale", "Unable to close content: " + uri);}
}private static Bitmap readBitmapData(Context context, Uri uri, BitmapFactory.Options options) {if (uri == null) {return null;}Bitmap bitmap = null;String scheme = uri.getScheme();if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||ContentResolver.SCHEME_FILE.equals(scheme)) {InputStream stream = null;try {stream = context.getContentResolver().openInputStream(uri);bitmap = BitmapFactory.decodeStream(stream, null, options);} catch (Exception e) {Log.e("readBitmapData", "Unable to open content: " + uri, e);} finally {if (stream != null) {try {stream.close();} catch (IOException e) {Log.e("readBitmapData", "Unable to close content: " + uri, e);}}}} else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {Log.e("readBitmapData", "Unable to close content: " + uri);} else {Log.e("readBitmapData", "Unable to close content: " + uri);}return bitmap;
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/414585.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第八届蓝桥杯-日期问题

标题&#xff1a;日期问题小明正在整理一批历史文献。这些历史文献中出现了很多日期。小明知道这些日期都在1960年1月1日至2059年12月31日。令小明头疼的是&#xff0c;这些日期采用的格式非常不统一&#xff0c;有采用年/月/日的&#xff0c;有采用月/日/年的&#xff0c;还有…

9、Flutter 实现 生成二维码

9、Flutter 实现 生成二维码 1、加入依赖 在 pubspec.yaml 中 dependencies 节点下添加&#xff1a; dependencies: qr_flutter: ^1.1.6 2、引入代码 在需要细线二维码的 dart 类中引入依赖代码包&#xff1a; import package:qr_flutter/qr_flutter.dart; 代码部分 import p…

工作244:根据页面的内容调用

1根据内容接口判断接口数据 2显示不同的内容 3状态管理 <!--首页管理--> <template><div><!--market--><el-card v-if"task1.length!0" style"width: 100%;height: 300px;"><el-carousel :interval"3000"…

Android 换肤demo,轻量快捷接入集成,判断是否夜间模式

true为黑夜模式 //检查当前系统是否已开启暗黑模式 public static boolean getDarkModeStatus(Context context) {int mode context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;return mode Configuration.UI_MODE_NIGHT_YES;} 实现…

Python——使用matplotlib绘制柱状图

Python——使用matplotlib绘制柱状图 1、基本柱状图 首先要安装matplotlib&#xff08;http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot&#xff09; 可以使用pip命令直接安装[python] view plaincopy # -*- coding: utf-8 -*- import matplotlib.pyplot a…

了解 yarn 、npm、nodejs

了解 yarn 、npm、nodejs 一、前言 针对即将上线的 jeecg-boot 做一些准备。二、了解系列 1、了解 nodejs Node.js 就是运行在服务端的 JavaScript。Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台。Node.js是一个事件驱动I/O服务端JavaScript环境&#xff0c;基于…

Android 语音播报,语音识别demo

该功能是基于百度智能云实现的根据文字进行语音播报。 1、首先到百度智能云创建语音应用 https://console.bce.baidu.com/ai/ 填写包名创建百度语音应用&#xff0c;获取AppID&#xff0c;API Key&#xff0c;Secret Key 2、导入资源文件。语音jar&#xff0c;assets语音库&am…

jeecg自定义datagrid查询

jeecg自定义datagrid查询 为什么要写这篇文章&#xff1f; 我们了解&#xff0c;使用 jeecg 提供的 CriteriaQuery 查询方式&#xff0c;确实能满足绝大数的需求&#xff0c;但是往往有那么个比较复杂的情况&#xff0c;需要我们直接去写 sql&#xff0c;比如多表查询呀等等等…

mailto发送邮件

mailto后面加发送邮件地址&#xff0c;可以在网页上通过链接直接打开邮件客户端发送邮件&#xff1b;只有第一个可以 1 <!DOCTYPE html>2 <html>3 <head>4 <meta charset"UTF-8">5 <title></title>6 &l…

Failed to resolve: org.jetbrains.kotlin:kotlin-stdlib-jre7:1.3.21

第一次在Android studio 创建kotlin项目。编译报错&#xff1a; Failed to resolve: org.jetbrains.kotlin:kotlin-stdlib-jre7:1.3.21 解决方法 // implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"implementation "org.jetbrai…

jeecg自定义按钮使用exp属性不起作用

jeecg自定义按钮使用exp属性不起作用 为什么要写这篇文章&#xff1f; 之前写过一篇类似的文章 jeecg笔记之自定义显示按钮exp属性&#xff0c;但是有些小伙伴留言参考后不起作用&#xff0c;当时我的 jeecg 版本为3.7.5&#xff0c;最终以版本不同&#xff0c;暂时搁浅了。今…

使用java修改图片DPI

修改以后可以直接用PS打开看效果 全部使用rt下的类&#xff0c;无需下载其他jar包 import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; import javax.imageio.ImageIO; …

Android studio 创建kotlin工程

1、安装kotlin插件 打开settings页面。安装插件 2、已安装kotlin插件即可创建kotlin项目 打开New Project。选中Includ Kotlin support即可 3、创建kotlin或者java的activity 选中语音类型kotlin或者java kotlin项目创建完成 kotlin工程demo链接&#xff1a;https://download…

改造一下jeecg中的部门树

改造一下jeecg中的部门树 假装有需求 关于 jeecg 提供的部门树&#xff0c;相信很多小伙伴都已经用过了&#xff0c;今天假装有那么一个需求 "部门树弹窗选择默认展开下级部门"&#xff0c;带着这个需求再次去探索一下吧。 一、改造之前的部门选择树流程 1.1 t:depa…

html 知识

一 html是什么&#xff1f; ,1、超文本标记语言&#xff08;Hypertext Markup Language, HTML&#xff09;是一种用于创建网页的标记语言。 2、本质上是浏览器可识别的规则&#xff0c;我们按照规则写网页&#xff0c;浏览器根据规则渲染我们的网页。对于不同的浏览器&#xff…

Android kotlin基础语法

1、继承类和实现接口 继承类是冒号连接&#xff0c;java是extends连接。实现接口是逗号连接&#xff0c;java是implements连接 class MainActivity : AppCompatActivity(),MyKotlinInterface ,MyInterface{ java&#xff1a;public class Main3Activity extends AppCompatAc…