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提供了一系列静态方法加载不同来源的图片。
    
        }
    
        }

    位图缩放可以优化内存

  • 相关阅读:
    python编码小记
    eventlet学习笔记
    python库文件路径
    paste deploy初探
    python浅拷贝与深拷贝
    Javascript basic knowledge
    用大数据学习心理学
    Postgres Database management operations
    Python Socket and WSGI Sample
    Failed to connect socket to '/var/run/libvirt/libvirt-sock': No such file or directory错误处理
  • 原文地址:https://www.cnblogs.com/Ocean123123/p/10966284.html
Copyright © 2011-2022 走看看