zoukankan      html  css  js  c++  java
  • Bitmap缩放(二)

    先得到位图宽高不用加载位图,然后按ImageView比例缩放,得到缩放的尺寸进行压缩并加载位图.inSampleSize是缩放多少倍,小于1默认是1,通过调节其inSampleSize参数,比如调节为2,宽高会为原来的1/2,内存变回原来的1/4.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:id="@+id/line1"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="300dp" />
    
    </LinearLayout>

    布局文件

    public class MainActivity extends AppCompatActivity {
    
        @Override
    
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ImageView imageView = findViewById(R.id.image);
    
            BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
    // 不将图片读取到内存中,仍然可以通过参数获得它的高宽
            factoryOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeFile("/sdcard/AAAImage/image2.png", factoryOptions);
            int imageWidth = factoryOptions.outWidth;
            int imageHeight = factoryOptions.outHeight;
    
            ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
            int width2 = layoutParams.width;
            int height2 = layoutParams.height;
            // 等比缩小,previewWidth和height是imageView的宽高
            int scaleFactor = Math.max(imageWidth /width2,
                    imageHeight /height2);
    
    // 将图片读取到内存中
            factoryOptions.inJustDecodeBounds = false;
    // 设置等比缩小图
            factoryOptions.inSampleSize = scaleFactor;
    // 样图可以回收内存
            factoryOptions.inPurgeable = true;
         Bitmap uploadImage = BitmapFactory
                    .decodeFile("/sdcard/AAAImage/image2.png", factoryOptions);
    
            imageView.setImageBitmap(uploadImage);
    //加载显示一符图像,对内存的使用有显著影响,BitmapFactory提供了一系列静态方法加载不同来源的图片。
    
        }
    
        }

    位图缩放可以优化内存

  • 相关阅读:
    javablogs
    Android学习笔记WIFI设备
    线程
    初次尝试Chrome扩展开发——以幻灯片方式显示网页内的图片
    could not find the main class, Program will exit(已解决)
    tomcat6.0配置(含配置视频下载)
    Windows下JDK1.6.0+Tomcat6.0的安装配置
    Java学习
    【翻译】在没有安装ASP.NET MVC3的服务器上运行ASP.NET MVC3的程序scottgu
    AForge.NET框架的使用
  • 原文地址:https://www.cnblogs.com/Ocean123123/p/10966284.html
Copyright © 2011-2022 走看看