Android图像介绍——利用bitmap加载图片文件并表示

我们写一个图片加载的例子,使用不同的方式加载图片文件。

首先将图片文件放到res/drawable目录下:

同样也需要将图片文件放到虚拟机sdcard/Pictures目录下:

XML文件如下:

<?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:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="40dp"
            android:layout_height="40dp" />


        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="60dp"
            android:layout_height="60dp" />


        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="80dp"
            android:layout_height="80dp" />


        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="100dp"
            android:layout_height="100dp" />


        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="120dp"
            android:layout_height="120dp" />
        <ImageView
            android:id="@+id/imageView6"
            android:layout_width="140dp"
            android:layout_height="140dp" />


</LinearLayout>

MyBitmap代码如下:

package com.example.bitmapdomo;


import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;


import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;


public class MyBitmap {


    public static Bitmap readBitmapFromResource(Resources resources, int resourcesId, int reqWidth, int reqHeight){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources,resourcesId,options);
        float srcWidth = options.outWidth;
        float srcHeight = options.outHeight;
        int inSampleSize = 1;


        if(srcHeight > reqHeight || srcWidth > reqWidth){
            if(srcWidth > srcHeight){
                inSampleSize = Math.round(srcHeight/reqHeight);
            }else{
                inSampleSize = Math.round(srcWidth/reqWidth);
            }
        }


        options.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;


        Log.i("MainActivity","readBitmapFromResource Bitmap srcWidth=" + srcWidth +
                " srcHeight=" + srcHeight + " inSampleSize=" + inSampleSize);


        return BitmapFactory.decodeResource(resources,resourcesId,options);
    }


    public static Bitmap readBitmapFromFile(String filePath, int reqWidth, int reqHeight) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, options);
            float srcWidth = options.outWidth;
            float srcHeight = options.outHeight;
            int inSampleSize = 1;


            if (srcHeight > reqHeight || srcWidth > reqWidth) {
                if (srcWidth > srcHeight) {
                    inSampleSize = Math.round(srcHeight / reqHeight);
                } else {
                    inSampleSize = Math.round(srcWidth / reqWidth);
                }
            }


            options.inJustDecodeBounds = false;
            options.inSampleSize = inSampleSize;


            Log.i("MainActivity", "readBitmapFromFile Bitmap srcWidth=" + srcWidth +
                    " srcHeight=" + srcHeight + " inSampleSize=" + inSampleSize);


            return BitmapFactory.decodeFile(filePath, options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static Bitmap readBitmapFromFileDescriptor(String filePath, int reqWidth, int reqHeight){
        try{
            FileInputStream fileInputStream = new FileInputStream(filePath);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(fileInputStream.getFD(),null,options);
            float srcWidth = options.outWidth;
            float srcHeight = options.outHeight;
            int inSampleSize = 1;


            if (srcHeight > reqHeight || srcWidth > reqWidth) {
                if (srcWidth > srcHeight) {
                    inSampleSize = Math.round(srcHeight / reqHeight);
                } else {
                    inSampleSize = Math.round(srcWidth / reqWidth);
                }
            }


            options.inJustDecodeBounds = false;
            options.inSampleSize = inSampleSize;


            Log.i("MainActivity", "readBitmapFromFileDescriptor Bitmap srcWidth=" + srcWidth +
                    " srcHeight=" + srcHeight + " inSampleSize=" + inSampleSize);


            return BitmapFactory.decodeFileDescriptor(fileInputStream.getFD(),null, options);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public static Bitmap readBitmapFromInputStream(InputStream inputStream){
        return BitmapFactory.decodeStream(inputStream);
    }


    public static Bitmap readBitmapFromInputStream(InputStream inputStream, int reqWidth, int reqHeight){


        byte[] buffer = inputStreamToBytes(inputStream);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        BitmapFactory.decodeByteArray(buffer,0,buffer.length,options);
        float srcWidth = options.outWidth;
        float srcHeight = options.outHeight;
        int inSampleSize = 1;


        if (srcHeight > reqHeight || srcWidth > reqWidth) {
            if (srcWidth > srcHeight) {
                inSampleSize = Math.round(srcHeight / reqHeight);
            } else {
                inSampleSize = Math.round(srcWidth / reqWidth);
            }
        }


        options.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;


        Log.i("MainActivity", "readBitmapFromInputStream Bitmap srcWidth=" + srcWidth +
                " srcHeight=" + srcHeight + " inSampleSize=" + inSampleSize);
        return BitmapFactory.decodeByteArray(buffer,0,buffer.length,options);
    }


    public static Bitmap readBitmapFromByteArray(byte[] data, int reqWidth, int reqHeight){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data,0,data.length,options);
        float srcWidth = options.outWidth;
        float srcHeight = options.outHeight;
        int inSampleSize = 1;


        if (srcHeight > reqHeight || srcWidth > reqWidth) {
            if (srcWidth > srcHeight) {
                inSampleSize = Math.round(srcHeight / reqHeight);
            } else {
                inSampleSize = Math.round(srcWidth / reqWidth);
            }
        }


        options.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;


        Log.i("MainActivity", "readBitmapFromByteArray Bitmap srcWidth=" + srcWidth +
                " srcHeight=" + srcHeight + " inSampleSize=" + inSampleSize);


        return BitmapFactory.decodeByteArray(data,0,data.length,options);
    }


    public static Bitmap drawableToBitmap(Drawable drawable){
        Bitmap bitmap = null;


        if(drawable instanceof BitmapDrawable){
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            if(bitmapDrawable.getBitmap() != null){
                return bitmapDrawable.getBitmap();
            }
        }


        if((drawable.getIntrinsicWidth() <= 0) || (drawable.getIntrinsicHeight() <= 0)){
            bitmap = Bitmap.createBitmap(1,1,Bitmap.Config.ARGB_8888);
        }else{
            bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(), Bitmap.Config.RGB_565);
        }


        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }


    public static Drawable bitmapToDrawable(Context context, Bitmap bitmap){
        return new BitmapDrawable(context.getResources(),bitmap);
    }


    public static byte[] bitmapToBytes(Bitmap bitmap){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream);
        return  byteArrayOutputStream.toByteArray();
    }


    public static byte[] inputStreamToBytes(InputStream inputStream) {
        ByteArrayOutputStream  byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];


        try {
            int num = inputStream.read(buffer);
            while (num != -1) {
                byteArrayOutputStream.write(buffer, 0, num);
                num = inputStream.read(buffer);
            }
            byteArrayOutputStream.flush();


        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toByteArray();
    }


    public static InputStream bytesToInputStream(byte[] buffer){
        return new ByteArrayInputStream(buffer);
    }
}

Activity代码如下:

package com.example.bitmapdomo;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;


import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;


public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE"};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        verifyStoragePermissions(this);
        initItem();
    }


    private void initItem(){
        ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
        ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
        ImageView imageView3 = (ImageView) findViewById(R.id.imageView3);
        ImageView imageView4 = (ImageView) findViewById(R.id.imageView4);
        ImageView imageView5 = (ImageView) findViewById(R.id.imageView5);
        ImageView imageView6 = (ImageView) findViewById(R.id.imageView6);


        imageView1.post(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = MyBitmap.readBitmapFromResource(
                        getResources(), R.drawable.bronya,
                        imageView1.getWidth(), imageView1.getHeight());


                Log.i("MainActivity","imageView1 Width=" + imageView1.getWidth()+
                        " Height="+imageView1.getHeight() +
                        " RowBytes="+bitmap.getRowBytes());


                imageView1.setImageBitmap(bitmap);
            }
        });


        imageView2.post(new Runnable() {
            @Override
            public void run() {
                String filePath = Environment.getExternalStorageDirectory().
                        getAbsolutePath() + "/Pictures/bronya.png";


                Bitmap bitmap = MyBitmap.readBitmapFromFile(
                        filePath, imageView2.getWidth(),imageView2.getHeight());


                Log.i("MainActivity","imageView2 Width=" + imageView2.getWidth()+
                        " Height="+imageView2.getHeight() +
                        " RowBytes="+bitmap.getRowBytes());


                imageView2.setImageBitmap(bitmap);
            }
        });


        imageView3.post(new Runnable() {
            @Override
            public void run() {
                String filePath = Environment.getExternalStorageDirectory().
                        getAbsolutePath() + "/Pictures/bronya.png";


                Bitmap bitmap = MyBitmap.readBitmapFromFileDescriptor(
                        filePath, imageView3.getWidth(),imageView3.getHeight());


                Log.i("MainActivity","imageView3 Width=" + imageView3.getWidth()+
                        " Height="+imageView3.getHeight() +
                        " RowBytes="+bitmap.getRowBytes());


                imageView3.setImageBitmap(bitmap);
            }
        });


        imageView4.post(new Runnable() {
            @Override
            public void run() {
                byte[] buffer = new byte[1024];
                InputStream inputStream = null;
                String filePath = Environment.getExternalStorageDirectory().
                        getAbsolutePath() + "/Pictures/bronya.png";


                try {
                    inputStream = new FileInputStream(filePath);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }


                Bitmap bitmap = MyBitmap.readBitmapFromInputStream(
                        inputStream,imageView4.getWidth(),imageView4.getHeight());


                Log.i("MainActivity","imageView4 Width=" + imageView4.getWidth()+
                        " Height="+imageView4.getHeight() +
                       " RowBytes="+bitmap.getRowBytes());


                imageView4.setImageBitmap(bitmap);
            }
        });


        imageView5.post(new Runnable() {
            @Override
            public void run() {
                Drawable drawable = getDrawable(R.drawable.bronya);
                Bitmap bitmap = MyBitmap.drawableToBitmap(drawable);


                Log.i("MainActivity","imageView5 Width=" + imageView5.getWidth()+
                        " Height="+imageView5.getHeight() +
                        " RowBytes="+bitmap.getRowBytes());


                imageView5.setImageBitmap(bitmap);
            }
        });


        imageView6.post(new Runnable() {
            @Override
            public void run() {
                byte[] buffer = new byte[1024];
                Drawable drawable = getDrawable(R.drawable.bronya);
                buffer = MyBitmap.bitmapToBytes(MyBitmap.drawableToBitmap(drawable));
                Bitmap bitmap = MyBitmap.readBitmapFromByteArray(
                        buffer,imageView6.getWidth(),imageView6.getHeight());


                Log.i("MainActivity","imageView6 Width=" + imageView6.getWidth()+
                        " Height="+imageView6.getHeight() +
                        " RowBytes="+bitmap.getRowBytes() +
                        " bytes length="+buffer.length);


                imageView6.setImageBitmap(bitmap);
            }
        });
    }


    private static void verifyStoragePermissions(Activity activity){
        try{
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.READ_EXTERNAL_STORAGE");


            if(permission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    initItem();
                }else{
                    Toast.makeText(this,"拒绝权限将无法使用程序",Toast.LENGTH_SHORT).show();
                    finish();
                }
        }
    }
}

由于需要SD文件读取权限,因此Manifest文件也需要追加如下语句:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

显示效果如下:

Log如下:

        通过Log可以看到不同大小的imageView设置的采样率不同,加载后的RowBytes大小也不同,但同样采样率从res/drawable加载的RowBytes会大一些,这个我也不知道啥原因。

Domo代码:

Android图像介绍-利用bitmap加载图片文件并表示资源-CSDN文库

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值