Android P实现Bitmap、Byte[]数组和Drawable之间的相互转换

Bitmap,byte[],Drawable相互转化 1、Drawable就是一个可画的对象,其可能是一张位图(BitmapDrawable),也可能是一个图形(ShapeDrawable),还有可能是一个图层(LayerDrawable),我们根据画图的需求,创建相应的可画对象2、Canvas画布,绘图的目的区域,用于绘图3、Bitmap位图,用于图的处理4、Matrix矩阵 立即下载

在安卓开发中,会经常用到将图片转化成byte[]数组保存或者传输,然后再将byte[]数组转换成图片格式,得到图片。

一、将图片转换成byte[]数组
public static byte[] bitmap2Bytes(Bitmap bitmap){
    if( null != bitmap ){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);	//注意压缩png和jpg的格式和质量
        return baos.toByteArray();
    }
    return null;
}
二、将byte[]数组转换成bitmap
public static Bitmap bytes2Bitmap(byte[] bytes, BitmapFactory.Options opts){
    if ( null != opts ){
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,opts);
    }else{
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }
}
三、将byte[]数组转换成图片文件并保存起来
private void bytes2ImageFile(byte[] bytes) {
    try {
    	//将文件保存在路径“/storage/emulated/0/demo.jpg”
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/demo.jpg");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bytes, 0, bytes.length);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
四、将bitmap转换成drawable
public Drawable bitmap2Drawable(Bitmap bitmap){
	new BitmapDrawable(getResources(), bitmap)
}

关于静态方法使用getResources()报错的问题:Non-static method ‘getResources()’ cannot be referenced from a static context
解决:

private static Context mContext = null;
mContext = getActivity();
public Drawable bitmap2Drawable(Bitmap bitmap){
	new BitmapDrawable(mContext.getResources(), bitmap)
}
五、将drawable转换成bitmap
public Bitmap drawable2bitmap(Drawable drawable){
	new ((BitmapDrawable) drawable).getBitmap();
}
保姆级教程:用ROS2 Humble和Nav2从零搭建一个能自主导航的机器人小车(含SLAM建图与避障) 本文提供了一份详细的保姆级教程,指导如何使用ROS2 Humble和Nav2从零搭建一个具备自主导航功能的机器人小车,包括SLAM建图与避障。教程涵盖了硬件组装、ROS2环境配置、URDF模型创建、SLAM建图实战、Nav2导航栈配置以及系统集成调试等关键步骤,适合机器人开发初学者和进阶开发者。 阅读详情

相关推荐

向量库深度解析:选型、索引原理与生产实践

本文系统解析五大主流向量库(pgvector、Milvus、Weaviate、ChromaDB、Faiss)的定位、优缺点与适用场景,深入拆解FLAT、IVF、HNSW等核心索引原理,并重点分析Milvus的Compaction机制。针对数据治理场景,提供精准选型建议:中小规模优先pgvector或Weaviate,超大规模选择Milvus,开发测试推荐ChromaDB。核心索引推荐HNSW,兼顾检索速度与召回率。全文从理论到实践,为开发者提供清晰的向量库选型逻辑与生产落地指南。

a123147abc的博客 362

BipMap.byte[],drawable相互转化

2 Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.icon); 2、Bitmap → byte[] 1 public byte[] Bitmap2Bytes(Bitmap bm) { 2 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 3

小妞妞 844

如何区分Info与CoWoS封装?

这篇文章主要从Info、CoWoS封装的定义、Interposer的种类以及Info、CoWoS封装的种类三方面进行了介绍,希望读者能够有所收获

wangyubo1的博客 7938

Android Drawable、Bitmap、byte[]之间的转换

Drawable –> BitmapBitmap drawable2Bitmap(Drawable drawable) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (draw

来啊 快活啊 1220

python 解析bag文件(不用安装ros系统)

在网上找了很多教程都是安装ros系统之后再通过ros自带的包来解析bag文件,但我并不想安装ros系统,之前我也是通过安装ros系统在来解析bag文件,我觉得不是很方便,主要有两点原因,(1)安装ros需要root用户权限(2)ros系统只支持Python2的接口,一般我都是Python3的conda环境,这样每次调用rosbag时都需要先把当前的conda环境注释掉,不然会报错,然后使用完毕在回到conda环境 ros本身是提供了C++和Python的接口,因为我目前的诉求就只是解析bag文件,我想肯定有

sabrinalx的博客 1万+

STM32--基于STM32F103C8T6的OV7670摄像头显示

使用 STM32F103C8T6 微控制器驱动 OV7670 摄像头模组,并将图像数据显示在屏幕上,是嵌入式系统中常见的图像采集与显示应用。OV7670 是一款 CMOS VGA 图像传感器,具有高灵敏度、低电压等特点,适用于嵌入式应用。而 STM32F103C8T6 是一款常用的 MCU 控制器,具有丰富的管脚资源和较高的工作频率。

duierrorshuobu的博客 2146

Android中Bitmap和Drawable

一、相关概念 1、Drawable就是一个可画的对象,其可能是一张位图(BitmapDrawable),也可能是一个图形(ShapeDrawable),还有可能是一个图层(LayerDrawable),我们根据画图的需求,创建相应的可画对象 2、Canvas画布,绘图的目的区域,用于绘图 3、Bitmap位图,用于图的处理 4、Matrix矩阵 二、Bitmap 1、从资源中获取Bit...

dyh7077063的博客 388

【深大算法设计与分析】实验六 最大流应用问题(棒球赛问题) 实验报告 附代码、数据集

【内附代码与数据集】【深大算法设计与分析】实验六 最大流应用问题(棒球赛问题)

m0_74268508的博客 1293

Android 之 Bitmap

Bitmap在Android中指的是一张图片,可以是png,也可以是jpg等其他图片格式。一、Bitmap的基本加载Bitmap的加载离不开BitmapFactory类,关于Bitmap官方介绍Creates Bitmap objects from various sources, including files, streams, and byte-arrays.查看api,发现和描述的一样,B...

holiday_ob的专栏 416

手把手教你用u-center配置ublox GPS模块:从波特率到报文频率全流程

本文提供了一份详细的u-center软件配置ublox GPS模块的完整指南。从硬件连接到软件设置,逐步讲解了如何探测并设置正确的波特率、选择与启用关键的NMEA和UBX报文,以及配置输出频率。文章特别强调了配置固化的重要性,并分享了使用UBX协议进行高效数据解析等高级技巧,帮助开发者快速上手并优化GPS模块性能。

weixin_28285943的博客 897

[RK3568 Android11] 开发之蓝牙(AP6275S)

前言 蓝牙是一种支持设备短距离通信(一般10m内)的无线电技术,能在包括移动电话、PDA、无线耳机、笔记本电脑、相关外设等众多设备之间进行无线信息交换。利用“蓝牙”技术,能够有效地简化移动通信终端设备之间的通信,也能够成功地简化设备与因特网Internet之间的通信,从而数据传输变得更加迅速高效,为无线通信拓宽道路。 接下来是在RK3568上调试AP6275S模块蓝牙部分: 一、设备树dts配置 根据硬件原理图,找到对应的控制引脚,配置好dts: ...

~未来可期~ 4074

java bitmap转换成byte数组_Bitmap转换成为byte数组

以下内容Sinfrancis版权所有,专注请注明来自 http://mdev.cc/dev通过ByteArrayOutputStream 转换public byte[] getBytesFromBitmap(Bitmap bmp) {try {int height = bmp.getHeight();int width = bmp.getWidth();int[] rgbdata = new i...

weixin_35829704的博客 1504

MIKE水动力笔记13_数字化海图2之克里金插值

在进行MIKE水动力建模之初,需要准备好水深数据,本专题系列博文主要讲解如何将扫描版JPG格式海图数据在ArcGIS中进行数字化并制作成xyz水深地形数据,用的克里金插值方法,仅供参考。

晏长街的博客 2881

Android中Bitmap、Drawable、byte[]转换

public byte[] getBitmapByte(Bitmap bitmap){ ByteArrayOutputStream out = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); try { ...

dianwei5413的博客 90

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

android id转化为bitmap,Android中Bitmap, Drawable, Byte,ID之间的转化

1. Bitmap 转化为 byteByteArrayOutputStream out = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);byte[] array= out.toByteArray();2. byte转化为bitmapBitmap bitmap = BitmapFa...

weixin_32349577的博客 593

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Android-Drawable、Bitmap、byte[]、资源文件相互转换

我们在Android的开发中,经常可以遇到图片的处理,当中,有很多是 Bitmap、Drawable、byte[]和资源文件它们直接相互转换。 今天就此总结一下: 1、资源文件转为Drawable 2、资源文件转为Bitmap 3、Bitmap转Drawable 4、Drawable转Bitmap 5、Bitmap转byte数组 6、Drawable转byte数组...

weixin_34138521的博客 538

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Drawable、Bitmap、byte[]之间的转换

android在处理一写图片资源的时候,会进行一些类型的转换:1 Drawable → Bitmap 的简单方法 1 ((BitmapDrawable)res.getDrawable(R.drawable.youricon)).getBitmap(); 2 Drawable → Bitmap 1 public static Bitmap drawableToBitmap(Dra...

weixin_30417487的博客 111

Android Bitmap与DrawAble与byte[]与InputStream之间的转换

public class FormatTools {      private static FormatTools tools = new FormatTools();        public static FormatTools getInstance() {          if (tools == null) {              tools = new FormatTo...

qq_33863614的博客 321

Android中Bitmap, Drawable, Byte,ID之间的转化

Android中Bitmap, Drawable, Byte,ID之间的转化 1. Bitmap 转化为 byte ByteArrayOutputStream out = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); byte[] array= out.toByteArray...

weixin_33726313的博客 94

BitMap、Drawable、inputStream及byte[] 互转

inputStream is=xxxx;                        BitmapDrawable bmpDraw=new BitmapDrawable(is);                        Bitmap bmp=bmpDraw.getBitmap();              Drawable →Bitmap              Bitma

天宝000专栏 415

Drawable和Bitmap转换

一、Bitmap转DrawableBitmap bm=xxx; //xxx根据你的情况获取BitmapDrawable bd=new BitmapDrawable(bm);因为BtimapDrawable是Drawable的子类,最终直接使用bd对象即可。二、 Drawable转Bitmap转成Bitmap对象后,可以将Drawable对象通过Android的SK库存成一个字节输出流,最终还可以保...

weixin_30662849的博客 61

Drawable与 Bitmap 常用方法

Drawable 使用方法详解请看上篇文章. 文章地址:http://www.jianshu.com/p/d67cfc946f59 本章主要涉及Drawable 常用的使用方法,主要包含以下内容 从资源中获取Bitmap Bitmap ----&gt; byte[] byte[] ----&gt; Bitmap Bitmap 缩放方法 Drawable ----&gt; Bitmap ...

程序员Android 361

转换Bitmap对象

把一个View转换bitmap对象 1 public static Bitmap getViewBitmap(View view) { 2 view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), 3 View.MeasureSpec.ma...

weixin_30591551的博客 103

Android 图片相关

从asset文件夹中读取Bitmap //从asset文件夹中取文件 private Bitmap getImageFromAssetFile(String fileName){ Bitmap image = null; try{ AssetManager am = this.get...

weixin_30699741的博客 60

Android 使用SQLite存储以及读取Drawable对象

在进行Android开发过程中,我们经常会接触到Drawable对象,那么,若要使用数据库来进行存储及读取,该如何实现? 一、存储 //第一步,将Drawable对象转化为Bitmap对象 Bitmap bmp = (((BitmapDrawable)tmp.image).getBitmap()); //第二步,声明并创建一个输出字节流对象 ByteArrayOutputStream...

weixin_30674525的博客 92
上一篇: Android P检测USB插入拔出消息并基于libaums实现读取USB文件
下一篇: Android中关于Socket通信数据大小,内存缓冲区和数据可靠性的一点调查
sunxiaolin2016
博客等级 码龄10年 221粉丝 205原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sunxiaolin2016

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值