大图片压缩后,保存小图片到本地

Android-Bitmap压缩策略 在这里我和身边一些朋友特意整理了一份快速进阶为Android高级工程师的系统且全面的学习资料。涵盖了Android初级——Android高级架构师进阶必备的一些学习技能。附上:我们之前因为秋招收集的二十套一二线互联网公司Android面试真题(含BAT、小米、华为、美团、滴滴)和我自己整理Android复习笔记(包含Android基础知识点、Android扩展知识点、Android源码解析、设计模式汇总、Gradle知识点、常见算法题汇总。 阅读详情

很多情况下,我们需要给服务器上传本地手机中的照片,但是手机照片的尺寸太大,好几兆,我们也没必须把这么大的照片上传给服务器,所以要压缩图片质量和尺寸,得到一个比较适应手机屏幕尺寸大小的照片。

这里没有把存放路径、压缩后图片大小,这些参数抽离出来,用户可在根据实际情况修改一下

目的:从本地path中获取bitmap,压缩后保存小图片到本地 涉及到的知识点:

  • 根据ImageView获取适当的压缩的宽和高,尽可能得到ImageView的精确的宽高
  • 通过反射获取imageview的某个属性值
  • 根据图片要显示的宽和高,对图片进行压缩,避免OOM
  • 根据需求的宽和高以及图片实际的宽和高计算SampleSize
package com.example.a.testduoxuantupian;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;

/**
 * Created by a on 2016/3/31.
 */
public class ImageUtils {
    /**
     * 从本地path中获取bitmap,压缩后保存小图片到本地
     *
     * @param context
     * @param path    图片存放的路径
     *                
     * @return 返回压缩后图片的存放路径
     */
    public static String saveBitmap(Context context, String path) {
        String compressdPicPath = "";

//      ★★★★★★★★★★★★★★重点★★★★★★★★★★★★★
      /*  //★如果不压缩直接从path获取bitmap,这个bitmap会很大,下面在压缩文件到100kb时,会循环很多次,
        // ★而且会因为迟迟达不到100k,options一直在递减为负数,直接报错
        //★ 即使原图不是太大,options不会递减为负数,也会循环多次,UI会卡顿,所以不推荐不经过压缩,直接获取到bitmap
        Bitmap bitmap=BitmapFactory.decodeFile(path);*/
//      ★★★★★★★★★★★★★★重点★★★★★★★★★★★★★

//        建议先将图片压缩到控件所显示的尺寸大小后,再压缩图片质量
//        首先得到手机屏幕的高宽,根据此来压缩图片,当然想要获取跟精确的控件显示的高宽(更加节约内存),可以使用getImageViewSize();
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;  // 屏幕宽度(像素)
        int height = displayMetrics.heightPixels;  // 屏幕高度(像素)
//        获取按照屏幕高宽压缩比压缩后的bitmap
        Bitmap bitmap = decodeSampledBitmapFromPath(path, width, height);

        String oldName = path.substring(path.lastIndexOf("/"), path.lastIndexOf("."));
        String name = oldName + "_compress.jpg";//★很奇怪oldName之前不能拼接字符串,只能拼接在后面,否则图片保存失败
        String saveDir = Environment.getExternalStorageDirectory()
                + "/compress";
        File dir = new File(saveDir);
        if (!dir.exists()) {
            dir.mkdir();
        }
        // 保存入sdCard
        File file = new File(saveDir, name);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

/* options表示 如果不压缩是100,表示压缩率为0。如果是70,就表示压缩率是70,表示压缩30%; */
        int options = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

        while (baos.toByteArray().length / 1024 > 500) {
// 循环判断如果压缩后图片是否大于500kb继续压缩

            baos.reset();
            options -= 10;
            if (options < 11) {//为了防止图片大小一直达不到500kb,options一直在递减,当options<0时,下面的方法会报错
                // 也就是说即使达不到500kb,也就压缩到10了
                bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
                break;
            }
// 这里压缩options%,把压缩后的数据存放到baos中
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }

        try {
            FileOutputStream out = new FileOutputStream(file);
            out.write(baos.toByteArray());
            out.flush();
            out.close();
            compressdPicPath = file.getAbsolutePath();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return compressdPicPath;
    }

    /**
     * 根据ImageView获取适当的压缩的宽和高
     * 尽可能得到ImageView的精确的宽高
     *
     * @param imageView
     * @return
     */
    public static ImageSize getImageViewSize(ImageView imageView) {

//      得到屏幕的宽度
        DisplayMetrics displayMetrics = imageView.getContext().getResources().getDisplayMetrics();


        ImageSize imageSize = new ImageSize();
        ViewGroup.LayoutParams lp = imageView.getLayoutParams();

//      ------------------------------------尽可能得到ImageView的精确的宽高-------------------------------------------------------------
//      得到imageView的实际宽度(为了压缩图片,这里一定要得到imageview的宽高)必须压缩!,否则OOM!!!!!!!!!!
        int width = imageView.getWidth();

        if (width <= 0) {//可能imageView刚new出来还没有添加到容器当中,width可能为0
            width = lp.width;//获取imageView在layout中声明的宽度
        }
        if (width <= 0) {//如果imageView设置的是WRAP_CONTENT=-1或者MATHC_PARENT=-2,得到的width还是0
            // TODO: 2016/3/19 此方法在API16以上才可以使用,为了兼容低版本,一会用反射获取,已解决
//            width = imageView.getMaxWidth();//检查最大值(此方法在API16以上才可以使用,为了兼容低版本,一会用反射获取)
            width = getImageViewFieldValue(imageView, "mMaxWidth");//检查最大值(此方法在API16以上才可以使用,为了兼容低版本,一会用反射获取)
        }
        if (width <= 0) {//如果还是得不到width,就设置为屏幕的宽度
            width = displayMetrics.widthPixels;
        }

//                                        ----------------------------------------

        //      得到imageView的实际高度(为了压缩图片,这里一定要得到imageview的宽高)必须压缩!,否则OOM!!!!!!!!!!
        int height = imageView.getHeight();

        if (height <= 0) {//可能imageView刚new出来还没有添加到容器当中,width可能为0
            height = lp.height;//获取imageView在layout中声明的高度
        }
        if (height <= 0) {//如果imageView设置的是WRAP_CONTENT=-1或者MATHC_PARENT=-2,得到的width还是0
            // TODO: 2016/3/19 此方法在API16以上才可以使用,为了兼容低版本,一会用反射获取,已解决
//            height = imageView.getMaxHeight();//检查最大值(此方法在API16以上才可以使用,为了兼容低版本,一会用反射获取)
            height = getImageViewFieldValue(imageView, "mMaxHeight");//检查最大值(此方法在API16以上才可以使用,为了兼容低版本,一会用反射获取)
        }
        if (height <= 0) {//如果还是得不到width,就设置为屏幕的高度
            height = displayMetrics.heightPixels;
        }
//       --------------------------------尽可能得到ImageView的精确的宽高------------------------------------------------------------------

        imageSize.width = width;
        imageSize.height = height;
        return imageSize;
    }

    /**
     * 通过反射获取imageview的某个属性值(imageView.getMaxWidth()这个方法在api16以上才可以用,所以使用反射得到这个width属性值)
     *
     * @param object
     * @param fieldName
     * @return
     */
    private static int getImageViewFieldValue(Object object, String fieldName) {

        int value = 0;

        try {
            Field field = ImageView.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            int fieldValue = field.getInt(object);
            if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE) {
                value = fieldValue;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


        return value;
    }

    /**
     * 根据图片要显示的宽和高,对图片进行压缩,避免OOM
     *
     * @param path
     * @param width  要显示的imageview的宽度
     * @param height 要显示的imageview的高度
     * @return
     */
    private static Bitmap decodeSampledBitmapFromPath(String path, int width, int height) {

//      获取图片的宽和高,并不把他加载到内存当中
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        options.inSampleSize = caculateInSampleSize(options, width, height);
//      使用获取到的inSampleSize再次解析图片(此时options里已经含有压缩比 options.inSampleSize,再次解析会得到压缩后的图片,不会oom了 )
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        return bitmap;

    }

    /**
     * 根据需求的宽和高以及图片实际的宽和高计算SampleSize
     *
     * @param options
     * @param reqWidth  要显示的imageview的宽度
     * @param reqHeight 要显示的imageview的高度
     * @return
     * @compressExpand 这个值是为了像预览图片这样的需求,他要比所要显示的imageview高宽要大一点,放大才能清晰
     */
    private static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int width = options.outWidth;
        int height = options.outHeight;

        int inSampleSize = 1;

        if (width >= reqWidth || height >= reqHeight) {

            int widthRadio = Math.round(width * 1.0f / reqWidth);
            int heightRadio = Math.round(width * 1.0f / reqHeight);

            inSampleSize = Math.max(widthRadio, heightRadio);

        }

        return inSampleSize;
    }



    /**
     * This method is used to get real path of file from from uri<br/>
     * http://stackoverflow.com/questions/11591825/how-to-get-image-path-just-
     * captured-from-camera
     * 这个方法是可以使用的(网上搜了一堆好多没用的代码)
     * @param contentUri
     * @return String
     */
    public static String getRealPathFromURI(Activity activity, Uri contentUri) {
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            // Do not call Cursor.close() on a cursor obtained using this
            // method,
            // because the activity will do that for you at the appropriate time
            Cursor cursor = activity.managedQuery(contentUri, proj, null, null,
                    null);
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            return contentUri.getPath();
        }
    }
}
package com.example.a.testduoxuantupian;

/**
 * 存放获取imageview高宽的一个类
 */
class ImageSize {
        public int width;
        public int height;
    }
Android Bitmap压缩图像的正确方法(compress的误区) 这两天在做的一个app需要从相册里面载入图片,踩了几个坑,这里Mark一下。 现在的相机基本都是800W+像素,差一点的手机1M多,好点的手机拍出来接近3M,如果直接载入图片,那非常容易造成oom,尤其是在差的手机上面。因此就需要对图像进行压缩处理。 先是在百度上搜了一把,比较多的解决方案都是使用Bitmap.compress()这个方法,那我也就跟着用了咯,使用形式如下: 阅读详情

相关推荐

bitmap.compress 参数解析,位图(Bitmap)是什么,bitmap和jpg,png区别

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out) 说明:(1)使用此方法压缩bitmap以后,图片的宽高大小都不会变化,每个像素大小也不会变化,所以图片在内存中的实际大小不会变化, (2)第二个参数是压缩比重,图片存储在磁盘上的大小会根据这个值变化。值越小存储在磁盘的图片文件越小, (3)第一个参数如果是Bitmap.CompressFo...

ZhangJiqun&191cm&85kg 2408

bitmap.compress方法说明

public static void saveBimap(Bitmap bitmap) { String name=MyApplication.getAppContext().getExternalCacheDir()+"/face.jpg"; LogUtils.i(TAG,"name="+name); File file = new Fil...

qq_29382145的博客 1万+

无符号整数、带符号整数溢出问题

让我们详细讲解一下带符号整数溢出和无符号整数溢出问题中,符号标志位 (SF)、零标志位 (ZF) 和进位标志位 (CF) 的行为方式

weixin_49342084的博客 2093

bitmap.compress(图片压缩的两种方式)(1,质量压缩;2,采样率压缩)

代码如下   ByteArrayOutputStream baos = new ByteArrayOutputStream();   image.compress(Bitmap.CompressFormat.JPEG, 100 , baos);   int options = 100 ;   while ( baos.toByteArray().length / 1024 > 32 )

RuiMan的博客 1万+

基于STM32和K210的自动驾驶小车设计

自动驾驶技术正在迅速发展,成为了汽车行业和智能交通领域的热点之一。随着科技的发展,STM32和K210这两款芯片为自动驾驶小车提供了优秀的硬件支持。本文我们将学习如何使用STM32和K210打造一个简单的自动驾驶小车。提示:以下是本篇文章正文内容,下面案例可供参考通过这篇文章,掌握了如何使用STM32和K210构建一个简单的自动驾驶小车。通过了解基本的电路设计,并编写了STM32和K210的代码。通过这个例子,可以更好地理解如何在嵌入式系统中使用STM32和K210,以及如何实现自动驾驶小车的简单功能。

Kyle_Chan_zMH的博客 2224

VS2022 中 std::mutex 静态初始化陷阱:一次诡异崩溃的排查记录

VS2022中使用std::mutex时遇到的静态初始化陷阱问题。该问题源于VS2022 17.4版本为std::mutex添加constexpr支持后,全局静态初始化可能导致系统资源未就绪时锁失效或崩溃。文章分析了问题现象、影响范围,并提供了解决方案。最后给出了排查清单和核心建议

qq_34552942的博客 953

大图片文件压缩保存本地,返回本地url

大图片文件压缩保存本地,返回本地url

太湖之子 533

从理论到实践:Zemax驱动下的离轴三反光学系统全流程构建

本文详细阐述了从理论推导到软件实现的离轴三反光学系统全流程设计方法。文章首先分析了离轴三反系统在空间遥感等领域的优势,然后手把手指导如何基于像差理论计算共轴三反的初始结构参数,包括曲率半径与圆锥系数。最后,重点介绍了在Zemax中完成从共轴建模、视场离轴设置到优化与性能评估的完整实战步骤,为光学工程师提供了宝贵的经验与避坑指南。

weixin_29205061的博客 241

Android 使用Glide4.9 压缩并保存图片(jpg/png/gif)到本地

项目中遇到,需要用户上传图片的场景。结果用户上传的、特别是拍摄后的图片,分辨率很大,长宽2000多3000甚至更高,一个图片5MB以上。 造成之后,从网络上加载这些图片,比较慢。 所以,不得不在上传前进行压缩后,再上传。

打渔还是晒网 —— stone 7649

FLUENT UDF编译及蒸发冷凝相关问题

蒸发冷凝与相间传质

weixin_48029137的博客 1万+

恒玄BES调试笔记-BES2500如何OTA升级ANC和通透参数

前期量产软件anc参数主要是通过anc工具写入flash中,或者anc total gain通过美格信设备校准写入,对于量产后如果想要更新anc参数,如通透模式参数,则无法更新。 这个时候需要通过OTA升级软件,把相关anc参数内置到软件中,从flash中读取total gain。 1、更新强弱降噪和通透参数,由于涉及到个人参数就不列出来了,主要是改动以下相关参数。 extern struct_anc_cfg * anc_coef_list_50p7k[ANC_COEF_...

leezs的博客 2226

保存到本地_表情包不能保存本地,玩了5年的微信,才知道可以这样批量保存...

用表情包表达情绪,交流感情。可谓好处多多不知道大家有没有遇到这样的困扰微信聊天看见别人发了一个很可爱的表情包——哇好喜欢——好想存手机发朋友圈、发微博、发空间一点击只能添加到表情并!没!有!存!到!本!地!的!选!项!就很气!想百度搜索找到原图,保存发现一搜出现了几千张图片,看的眼睛都瞎了。为了能更好的撩妹我小小的研究了一下天,就跟大家分享一下。【所需工具】① 电脑② 微信网页端登录【操作流程】1...

weixin_39819974的博客 2649

2025年7月12日全国青少年信息素养大赛图形化(Scratch)编程小学低年级组复赛真题+答案解析

2025年7月12日全国青少年信息素养大赛图形化(Scratch)编程小学低年级组复赛真题+答案解析

伶俐角少儿编程 713

Android 超清大尺寸图片压缩转Base64中卡顿/速度优化问题整理(在子线程压缩Bitmap卡的主线程进度条走不动了。。。)

最近遇到需求是前后端传输图片使用的是Base64,但是前端(Android 端)图片很大(尺寸很大4480 × 2520,质量也很大7-10M),需要压缩到一定尺寸(1280 × 960,当然还可以压得更小),然后传给后端,本来认为是一个简单的压缩,可是在子线程压缩过程中发现很卡,卡的主线程的进度条都走不动了,一开始用的模拟器测试的,以为模拟器性能比较差,可是换成手机测试,还是子线程压缩过程中很卡,卡的主线程的进度条都走不动了。为了解决这个问题,请看以下步骤: 1、先申请读写权限,要允许权限才可以进行之后

UrasakiNakajima的博客 5054

AD-Copilot 论文解读:把“大模型看图”升级为“对照检验”的工业异常检测助手

本文提出AD-Copilot,一个面向工业异常检测的视觉语言助手,通过视觉上下文比较解决现有方法的不足。针对工业场景中多模态大模型表现不佳的问题,作者指出核心原因在于缺乏工业数据和比较能力不足。为此,论文提出三个关键贡献:构建Chat-AD数据集,设计Comparison Encoder显式建模图像差异,以及采用多阶段训练策略。实验表明,该方法在MMAD基准上达到82.29%准确率,定位任务提升3.35倍,并展现出良好的泛化能力。消融实验验证了比较模块的有效性,表明其成功源于高质量比较数据与显式比较模块的协

blanokvaffy的博客 334

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

直播短视频系统,压缩图片为小尺寸

直播短视频系统,压缩图片为小尺寸 //压缩图片 int width = 200; using (var imgBmp = new Bitmap(@"d:\壁纸\b2.jpg")) { //找到新尺寸 int oWidth = imgBmp.Width; int oHeight = imgB

云豹网络科技 334

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

java实现图片压缩

import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.i...

Emine 521

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

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Android 开发图片压缩/缩略图的方法

FrameLayout fr=(FrameLayout)findViewById(R.id.FrameLayout01); BitmapFactory.Options options =new BitmapFactory.Options(); options.inJustDecodeBounds =true; // 获取这个图片的宽和...

weixin_34090643的博客 70

php将图片压缩成缩略图(大,中,小)上传到数据库中

1.思路 先用单文件上传将图片压缩成三个存放在本地,再用多文件上传,上传到数据库中代码:(这里的配置文件就不写了前面有);单文件上传压缩到本地://封装一个上传单个文件的方法 /* *@prame string key *@prame string path *@prame String maxSize *@prame array allowMime *@prame array allo

qq_33481269的博客 918

关于图片的存与读

场合: 在一个详细信息页面中,至少包含一个file控件和一个img控件。在新增时,用file加载一张本地图片,在img里显示,然后保存,将图片存入Oracle表中的Blob字段里;在读取时,读取Blob字段,将图片直接写入img控件,若图片大小过大,则对图片进行压缩。 页面部分代码: <div align="center" id="div1" runat="serve...

weixin_34067049的博客 179

Android实现图片压缩(大小与质量压缩以及图片保存)

Android实现图片压缩(大小与质量压缩以及图片保存) 这里写目录标题Android实现图片压缩(大小与质量压缩以及图片保存)前言:使用图片保存到本地 前言: Android中图片有四种属性,分别是: ALPHA_8:每个像素占用1byte内存 ARGB_4444:每个像素占用2byte内存 ARGB_8888:每个像素占用4byte内存 (默认) RGB_565:每个像素占用2byte内存 Android默认的颜色模式为ARGB_8888,这个颜色模式色彩最细腻,显示质

ZH-黑夜 4935

C#保存图片、压缩图片大小、缩放图片比例

一、保存web网络图片 /// <summary> /// 保存web图片到本地 /// </summary> /// <param name="FileName"></param> /// <param name="Url"></param> /// <returns></returns> public static bool SavePhotoFromUrl(string FileName, string U

欢迎道友来访 3859

Android压缩图片并且保存到本地内存卡中

亲爱的同学们,相信我们在软件开发中经常会遇到拍照,选择相册上传的功能。前几天遇到一个这样的一个问题。后台要求我上传的图片不能超过500KB,大家知道我们现在的智能手机像素越来越高,拍照的照片一般都是几兆甚至一二十兆。那么我们改怎么做呢,答案是一定的,那就是先进行压缩,然后在保存压缩后的图片上传。最近在网络上也搜索到了很多关于压缩的内容,相信大家会有和我同感,为什么都写的不清楚,或许我们可以实现我们

cdy的博客 公众号:Android开发吹牛皮 2745

base64转图片并压缩zip保存到本地(一)

在项目碰到这种需求,经过一番探索,终于实现了。如果正在看这篇博客的你,还有其他更好的方法,欢迎指出! 废话少说,直接上代码! 工具类:里面有文件夹 package com.eastyx.authentication.utils; import java.io.*; import java.util.List; import org.apache.tools.zip.ZipEntry; impo...

black_shooter的博客 3725

java获取远程网络图片文件流、压缩保存到本地

1.获取远程网路的图片 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 /** * 根据地址获得数据的字节流 * ...

ywl470812087的博客 12万+

UE4 如何将材质Material保存为本地图片Png

昨日不可追,今日尤可为.勤奋,炽诚,不忘初心 UE4 如何将材质Material保存为本地图片Png 下面这篇文章讲了如何将TextureRenderTarget2D保存为本地图片 https://blog.youkuaiyun.com/lunweiwangxi3/article/details/87457594 要...

迷雾森林的专栏 1万+
上一篇: Android存储(读取)之SharedPerference(最常用)
下一篇: 学会Retrofit,你可以参考的文章
Android_Study_OK
博客等级 码龄11年 91粉丝 128原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值