如何在Android中实现图片采样缩放功能?

在Android中,可以使用BitmapFactory.Options类来实现图片的采样缩放。以下是一个示例代码:,,“java,import android.graphics.Bitmap;,import android.graphics.BitmapFactory;,,public class ImageSampler {, public static Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight) {, // First decode with inJustDecodeBounds=true to check dimensions, final BitmapFactory.Options options = new BitmapFactory.Options();, options.inJustDecodeBounds = true;, BitmapFactory.decodeFile(path, options);,, // Calculate inSampleSize, options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);,, // Decode bitmap with inSampleSize set, options.inJustDecodeBounds = false;, return BitmapFactory.decodeFile(path, options);, },, private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {, // Raw height and width of image, final int height = options.outHeight;, final int width = options.outWidth;, int inSampleSize = 1;,, if (height > reqHeight || width > reqWidth) {, final int halfHeight = height / 2;, final int halfWidth = width / 2;,, // Calculate the largest inSampleSize value that is a power of 2 and keeps both, // height and width larger than the requested height and width., while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {, inSampleSize *= 2;, }, },, return inSampleSize;, },},“,,这个代码通过计算合适的inSampleSize来对图片进行采样缩放,从而减少内存占用并提高加载速度。

在Android开发中,图片采样和缩放是常见的需求,为了实现高效的图片处理,我们可以使用Bitmap类提供的方法进行图片的采样和缩放,下面是一个详细的实例代码,展示如何在Android应用中实现图片的采样和缩放功能

如何在Android中实现图片采样缩放功能?

1. 准备工作

我们需要在build.gradle文件中添加必要的依赖:

dependencies {
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.3.0'
}

2. 布局文件

创建一个简单的布局文件activity_main.xml,其中包含一个ImageView用于显示图片,以及两个按钮用于触发采样和缩放操作:

如何在Android中实现图片采样缩放功能?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
    <Button
        android:id="@+id/btnSample"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sample Image"
        android:layout_above="@id/imageView"
        android:layout_marginBottom="16dp"/>
    <Button
        android:id="@+id/btnScale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Scale Image"
        android:layout_below="@id/imageView"
        android:layout_marginTop="16dp"/>
</RelativeLayout>

3. MainActivity代码

MainActivity.javaMainActivity.kt中编写代码,实现图片的采样和缩放功能

Java版本

package com.example.imagesample;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private Button btnSample, btnScale;
    private Bitmap bitmap;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);
        btnSample = findViewById(R.id.btnSample);
        btnScale = findViewById(R.id.btnScale);
        // 加载原始图片
        bitmap = loadSampledBitmapFromResource(getResources(), R.drawable.large_image, 100, 100);
        imageView.setImageBitmap(bitmap);
        btnSample.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 重新采样图片
                bitmap = loadSampledBitmapFromResource(getResources(), R.drawable.large_image, 100, 100);
                imageView.setImageBitmap(bitmap);
            }
        });
        btnScale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 缩放图片
                Bitmap scaledBitmap = scaleBitmap(bitmap, 200, 200);
                imageView.setImageBitmap(scaledBitmap);
            }
        });
    }
    private Bitmap loadSampledBitmapFromResource(android.content.res.Resources res, int resId, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 先获取图片的宽高信息
        BitmapFactory.decodeResource(res, resId, options); // 解码图片但不返回bitmap对象
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 计算采样率
        options.inJustDecodeBounds = false; // 设置false以实际解码图片
        return BitmapFactory.decodeResource(res, resId, options); // 解码并返回bitmap对象
    }
    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }
    private Bitmap scaleBitmap(Bitmap bitmap, int newWidth, int newHeight) {
        return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
    }
}

Kotlin版本

package com.example.imagesample
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.io.InputStream
class MainActivity : AppCompatActivity() {
    private lateinit var bitmap: Bitmap
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 加载原始图片
        bitmap = loadSampledBitmapFromResource(resources, R.drawable.large_image, 100, 100)
        imageView.setImageBitmap(bitmap)
        btnSample.setOnClickListener {
            // 重新采样图片
            bitmap = loadSampledBitmapFromResource(resources, R.drawable.large_image, 100, 100)
            imageView.setImageBitmap(bitmap)
        }
        btnScale.setOnClickListener {
            // 缩放图片
            val scaledBitmap = scaleBitmap(bitmap, 200, 200)
            imageView.setImageBitmap(scaledBitmap)
        }
    }
    private fun loadSampledBitmapFromResource(res: android.content.res.Resources, resId: Int, reqWidth: Int, reqHeight: Int): Bitmap {
        val options = BitmapFactory.Options().apply { inJustDecodeBounds = true } // 先获取图片的宽高信息
        BitmapFactory.decodeResource(res, resId, options) // 解码图片但不返回bitmap对象
        inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight) // 计算采样率
        inJustDecodeBounds = false // 设置false以实际解码图片
        return BitmapFactory.decodeResource(res, resId, options) // 解码并返回bitmap对象
    }
    private fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
        var height = options.outHeight
        var width = options.outWidth
        var inSampleSize = 1
        if (height > reqHeight || width > reqWidth) {
            val halfHeight = height / 2
            val halfWidth = width / 2
            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2
            }
        }
        return inSampleSize
    }
    private fun scaleBitmap(bitmap: Bitmap, newWidth: Int, newHeight: Int): Bitmap {
        return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true)
    }
}

4. 资源文件

将一张大尺寸的图片(例如large_image.jpg)放置在res/drawable目录下,确保图片的尺寸足够大,以便能够明显看到采样和缩放的效果。

如何在Android中实现图片采样缩放功能?

5. 运行效果

启动应用后,点击“Sample Image”按钮会重新采样图片,使其适应指定的宽度和高度;点击“Scale Image”按钮则会对图片进行缩放,改变其尺寸,通过这两个操作,可以观察到图片在不同处理方式下的效果差异。

原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/1266351.html

本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。

(0)
未希
上一篇 2024-11-06 05:01
下一篇 2024-11-06 05:11

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

产品购买 QQ咨询 微信咨询 SEO优化
分享本页
返回顶部
云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购 >>点击进入