最实用的Android图片内存优化的方法

Android 中对于图片的内存优化方法 1. 对图片本身进行操作 尽量不要使用 setImageBitmap、setImageResource、 BitmapFactory.decodeResource 来设置一张大图,因为这些方法在完成 decode 后,最终都是通过 Java 层的 createBitmap 来完成的,需要消耗更多内存。因此,改用先通过 BitmapFactory.decodeStream 方法,创建出一个 bitmap,再将其设为 ImageView 的 source,decodeStream 最大的秘密在于其直接调用 JNI>>nativeDecodeAsset() 来完成 decode,无需再使用 Java 立即下载

习惯性的开始之前,美图镇楼

好好努力,大家都能美女簇拥

在实际开发过程中,我们经常会遇到所开发的APP加载缓慢甚至卡顿的问题,很大一部分原因就是图片造成的,这篇文章将对Android的图片进行优化以实现对性能的优化。

Android图片OOM问题的产生

可能的原因有以下3点:

  1. 一个页面一次加载过多的图片。 可能少量的图片加载对性能没有多大的影响,但是大量的图片对内存的占用是很可观的,而每个APP都是有内存限制的,大量的图片加载就可能直接超过了APP的内存限制,而直接OOM;
  2. 加载大图片没有进行压缩(尺寸,质量)。 对于大图片直接使用imageView.setImageResource()是不行的,需要对尺寸或质量进行优化;
  3. Android列表加载大量bitmap没有使用缓存。 需要使用缓存重用或者比较流行的图片加载框架如Glide,Fresco等,也是自带缓存功能的。

如何计算一张图片占用的内存?

一张图片占用的内存 = 图片的高度 * 图片的宽度 * 一个像素所占的内存

从这里我们就可以看出,对于图片优化可以从以下3个方面入手:

  1. 尺寸压缩; ps:就是减小图片的宽高。
    BitmapFactory.Options里面有个inJustDecodeBounds设置为true,就可以在不加载图片内存的情况下获取图片的宽高。从而计算出合适的压缩比inSampleSize,设置inSampleSize大于等于2,就可以降低图片的采样率,从而减小内存的占用。如果我们单纯的改变ImageView的大小不会对图片占用的内存有任何的优化作用,因为图片是存储在bitmap里面,只有对bitmap本身的优化才会起作用。

  2. 质量压缩; ps:就是改变一个像素占用的内存,内部是通过优化解码率来实现的。
    也就是解码率压缩,常见的PNG,JPG,WEBP等格式的图片在设置到UI上之前经过解码过程。通过解码率方面优化图片占用内存的方式:使用RGB_565替代ARGB_8888可以降低图片占用内存。因为它可以降低一个像素占用的内存大小,RGB_565的一个像素占2个字节,而ARGB_8888一个像素占4个字节。

  3. 内存重用; ps:可以通过Android提供的InBitmap来实现。
    InBitmap是Android3.0之后才能用的,使用了InBitmap的图片的内存大小是小于或者等于没有使用的图片内存大小。

代码演示(原图加载)

    /**
     * 加载原图
     * @param img 目标ImageView控件
     * @param filePath 图片路径
     */
    private void loadOriginalSize(ImageView img, String filePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
        img.setImageBitmap(bitmap);
    }

代码演示(图片压缩)

    /**
     * 压缩图片
     * @param img
     * @param filePath
     */
    private void picOptimize(ImageView img, String filePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        //设置为true,就可以在不加载图片内存的情况下获取图片的宽高
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        //获取图片宽度
        int width = options.outWidth;
        //计算出合适的压缩比,width压缩到200px
        options.inSampleSize = width / 200;
        //降低每个像素所占的内存大小,一个像素只占用两个字节
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        //真正把压缩后的图片加载出来
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
        img.setImageBitmap(bitmap);
    }
}

代码演示(内存重用)

    /**
     * inBitmap的使用,内存重用
     * @param secondImg 第二张图片的控件
     * @param filePath 第二张图片的路径
     * @param firstBitmap 第一张图片的bitmap(第二张图片的内存将重用这个bitmap的内存)
     */
    private void picInBitmap(ImageView secondImg, String filePath, Bitmap firstBitmap) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inBitmap = firstBitmap;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
        secondImg.setImageBitmap(bitmap);
    }

好了,图片的内存优化就到这里,后续还有关于图片缓存,懒加载的文章,关注我查看对应的文章。

Windows下Maven环境变量配置避坑指南:解决‘mvn‘不被识别问题 本文详细解析了Windows系统中配置Maven环境变量时常见的'mvn'不被识别问题,特别是当系统提示“无法将‘mvn’项识别为cmdlet、函数、脚本文件或可运行程序的名称”时的解决方案。文章从问题根源入手,提供了清晰的配置步骤、深入的排查方法以及针对PowerShell的特殊处理,旨在帮助开发者彻底解决环境变量配置难题,确保Maven命令正常使用。 阅读详情

相关推荐

PDMS二次开发入门:手把手教你用PML2写第一个交互式窗体工具

本文详细介绍了如何使用PML2进行AVEVA PDMS二次开发,从零开始构建交互式窗体工具。通过PML2语言的面向对象特性、即时调试能力和深度系统集成优势,开发者可以高效创建自动化设计工具、批量修改属性和定制报表系统。文章包含开发环境配置、基础语法、窗体架构设计、事件处理等实战内容,帮助读者快速掌握PDMS二次开发技能。

weixin_29281941的博客 271

android imageView释放内存

当一个界面里有很多张图片,而且图片加载切换很频繁,一个很好的机制可以保证整个功能流畅而无问题,在对于新手来说就头疼了,这时,ImageView所占的内存释放就显得很重要了。 ImageView释放内存的方法很简单,获取imageView对应的drawable,在获取其中的bitmap, bitmap.recycle(); bitmap =null; 而在开发过中,ImageView往往

Fling_Pig的博客 5540

超临界二氧化碳发电技术深度解析

超临界二氧化碳发电技术正在突破传统热电转换的物理边界。作为新一代发

硬核科技 601

ImageView内存清理

一般情况下,ImageView占用内存比较大,所以回收ImageView,就是一个很有必要的事情! 在App的引导页,一般会有几张图片来进行引导介绍APP的大致情况,但是此时内存消耗过多,所以需要做一下回收! 在Activity结束后,要想清理掉内存,首先要让imageView释放掉图片,然后在释放ImageView组件本身。代码如下: Intent loginIntent = new In

Go贝壳 1852

YTM32B1M SDK解析31:软件I2C驱动详解

YTM32B1M微控制器软件I2C驱动解析 本文详细介绍了YTM32B1M微控制器中通过GPIO引脚模拟I2C总线的软件实现方案。核心内容包括: 驱动架构:采用swi2c_config_t配置结构体和swi2c_state_t状态结构体管理I2C参数 功能接口:提供初始化、数据传输(主/从模式)、底层控制等API 应用示例:包含基本配置、EEPROM读写、传感器数据采集、总线扫描等典型应用场景 优化建议:给出引脚选择、时序配置、错误处理等方面的最佳实践 该驱动在硬件I2C资源不足时提供可靠替代方案,支持标准

VehSwHwDeveloper的博客 158

Oracle EBS Interface/API(43) -自定义AP发票状态说明API

在某项目,客户需求获得AP发票的状态说明,例如对账系统或者某些报表。由于标准系统未提供状态说明,需要通过AP发票的标准Form获得相关业务逻辑,然后自定义AP发票状态说明API。

陈显平的专栏-Oracle EBS 605

APP及时回收图片,释放内存的方法

APP占用内存很大一部分是因为把图片读到缓存里面了,如果在关闭activity或者fragment或者dialog等的时候,不及时回收图片资源,就会越积越多,APP越来越卡。 解决办法: 及时recycle掉bitmap占用的内存 //缓存图片回收 public static void recycleBitmap(Drawable drawable){         if (dra

wangic的博客 956

GEE 案例分析:利用Landsat数据进行FAI、NDVI及CHLA分析并统计平均值(巢湖为例)

浮游藻类指数(FAI)、归一化植被指数(NDVI)及叶绿素a(CHLA)是水体环境监测的重要指标。本文利用Google Earth Engine(GEE)平台,基于Landsat 5和Landsat 8数据,进行水体藻类及植被监测。

此星光明博客 1336

android内存分析、加载本地图片内存优化

从网上学习了MAT插件来查看内存使用情况,分析之后发现手上的应用对本地图片这边的内存损耗很大,查了相关资料之后发现,如果采用setImageBitmap、setImageResource这些来加载本地资源,会产生较大的损耗。因为这些方法在完成 decode 后,最终都是通过 Java 层的 createBitmap 来完成的,需要消耗更多内存。因此,改用先通过 BitmapFactory.deco...

weixin_30483013的博客 115

经典的YOLOv3和YOLOV5算法详解及代码复现

yolov3和yolov5算法详解及代码复现

hasakie的博客 769

深度学习工具包 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")

android如何释放图片缓存

转自:http://my.oschina.net/u/1753339/blog/223379 在你应用程序的UI界面加载一张图片是一件很简单的事情,但是当你需要在界面上加载一大堆图片的时候,情况就变得复杂起来。在很多情况下,(比如使用ListView, GridView 或者 ViewPager 这样的组件),屏幕上显示的图片可以通过滑动屏幕等事件不断地增加,最终导致OOM。 为了保证

lizhenmingdirk的专栏 1万+

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Android:最全面&详细的性能优化攻略(含内存优化、内存泄漏、绘制优化、布局优化、图片优化、APK优化、多线程优化、列表优化等)

前言:佛教中有一句话:初学者的心态,拥有初学者心态是件了不起的事情。真正的大师永远怀有一颗学徒的心。 一、概述 在Android中,性能优化非常重要,因为这决定这一个APP的质量好坏,一个更快更稳更省的app能给用户更优秀的体验。 更快:App流畅不卡顿,快速响应; 更稳:App稳定运行,程序不崩溃(Crash)和无响应(ANR); 更省:节省资...

https://juejin.cn/user/1654096907477549/posts 1万+

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

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

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

Android内存优化之图片优化

关于图片优化,大概如下 为什么要进行图片优化 相信大概刚开始学习Android的时候有过图片过大而直接报错的情况,下面简单介绍一下OOM问题,Android支持的图片格式及图片优化的几种方式 什么是OOM?:Android系统的进程(APP级别)有最大的内存限制,超过这个限制系统就会抛出)OOM错误 图片OOM问题产生的几种情况 1.一个页面一次加载过多的图片 2.加载大图片没有进行压缩 3....

计蒙不吃鱼的博客 1万+

Android中对图片的内存优化方法

另外,decodeStream 直接拿图片来读取字节码了,不会根据机器的各种分辨率来自动适应,使用了 decodeStream 之后,需要在 hdpi 和 mdpi,ldpi 中配置相应的图片资源, 否则在不同分辨率机器上都是同样大小(像素点数量),显示出来的大小就不对了。图片对象的本地数据占用的内存最大,而且与程序 Java 部分的内存是分开计算的。放大后的图片使用的 ARGB_8888 颜色模式,就算原图片是ARGB_4444 颜色模式也一样,而且没有办法在放大时直接指定颜色模式。

2401_85763997的博客 811

安卓图片内存优化(一)——图片占用内存大小的计算

1.图片的分辨率2.采用的色彩格式本地图片跟加载到内存后的图片占用空间的大小之所以会差别很大,原因是因为本地的图片正常都是经过一定压缩的,但是只是压缩图片质量而已,并不会改变分辨率。所以你把一张图片压缩后输出到本地,再把该图片和原图加载到内存后会发现两张图片占用的内存大小是一样的,因为两张图片的分辨率是一样的。

liuliuhelingdao的博客 1746

Android 图片内存优化

文章目录设置位图格式inSampleSizeinScaled ,inDensity 和 和 inTargetDensityinBitmap 在应用中有很多图片需要显示,这种图片可以是多种格式,如 JPEG、PNG 或者 WEBP,这种图片文件并不是很大,为了使文件变小,以提高传输速度,都要经过不同的压缩算法把位图压缩成不同的格式,但要在Android中显示图片,就和图片文件的大小无关了,在Andr...

Lud的博客 565
上一篇: 微信小程序关于we-cropper框架对各类机型适配问题 - 已解决
下一篇: Android常见的几种图片加载框架
盛国强
博客等级 码龄11年 105粉丝 22原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值