首页 > 其他 > 详细

BitmapUtil【缩放bitmap以及将bitmap保存成图片到SD卡中】

时间:2017-10-07 22:30:03      阅读:322      评论:0      收藏:0      [点我收藏+]

版权声明:本文为博主原创文章,未经博主允许不得转载。

前言

用于缩放bitmap以及将bitmap保存成图片到SD卡中

效果图

技术分享

代码分析

bitmapZoomByHeight(Bitmap srcBitmap, float newHeight): 根据指定的高度进行缩放(src是bitmap)

bitmapZoomByHeight(Drawable drawable, float newHeight) :根据指定的高度进行缩放(src是drawable)

bitmapZoomByScale(Bitmap srcBitmap, float scaleWidth, float scaleHeight): 根据指定的宽度比例值和高度比例值进行缩放

drawableToBitmap(Drawable drawable) :将drawable对象转成bitmap对象

saveBitmapToSDCard(Bitmap bitmap, String path): 将bitmap对象保存成图片到sd卡中

getBitmapFromSDCard(String path) :从sd卡中去除图片的bitmap对象

使用步骤

一、项目组织结构图

 技术分享

注意事项:

1、  导入类文件后需要change包名以及重新import R文件路径

2、  Values目录下的文件(strings.xml、dimens.xml、colors.xml等),如果项目中存在,则复制里面的内容,不要整个覆盖

二、导入步骤

将BitmapUtil复制到项目中

package com.why.project.bitmaputildemo.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by HaiyuKing
 * Used
 */

public class BitmapUtil {
    public static Bitmap temp;

    /**根据指定的高度进行缩放(source是bitmap)*/
    public static Bitmap bitmapZoomByHeight(Bitmap srcBitmap, float newHeight) {
        float scale = newHeight / (((float)srcBitmap.getHeight()));
        return BitmapUtil.bitmapZoomByScale(srcBitmap, scale, scale);
    }
    /**根据指定的高度进行缩放(source是drawable)*/
    public static Bitmap bitmapZoomByHeight(Drawable drawable, float newHeight) {
        Bitmap bitmap = BitmapUtil.drawableToBitmap(drawable);
        float scale = newHeight / (((float)bitmap.getHeight()));
        return BitmapUtil.bitmapZoomByScale(bitmap, scale, scale);
    }

    /**根据指定的宽度比例值和高度比例值进行缩放*/
    public static Bitmap bitmapZoomByScale(Bitmap srcBitmap, float scaleWidth, float scaleHeight) {
        int width = srcBitmap.getWidth();
        int height = srcBitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(srcBitmap, 0, 0, width, height, matrix, true);
        if(bitmap != null) {
            return bitmap;
        }else {
            return srcBitmap;
        }
    }

    /**将drawable对象转成bitmap对象*/
    public static Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }

    /**将bitmap对象保存成图片到sd卡中*/
    public static void saveBitmapToSDCard(Bitmap bitmap, String path) {

        File file = new File(path);
        if(file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ((OutputStream)fileOutputStream));
            fileOutputStream.close();
            System.out.println("----------save success-------------------");
        }
        catch(Exception v0) {
            v0.printStackTrace();
        }

    }
    /**从sd卡中去除图片的bitmap对象*/
    public static Bitmap getBitmapFromSDCard(String path) {

        Bitmap bitmap = null;
        try {
            FileInputStream fileInputStream = new FileInputStream(path);
            if(fileInputStream != null) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                bitmap = BitmapFactory.decodeStream(((InputStream) fileInputStream), null, options);
            }
        } catch(Exception e) {
            return null;
        }

        return bitmap;
    }


}

在AndroidMainfest.xml文件中声明权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.why.project.bitmaputildemo">

    <!-- =================BitmapUtil用到的权限========================== -->
    <!-- 允许程序读取外部存储文件 -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <!-- 允许程序写入外部存储,如SD卡上写文件 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

添加运行时权限的处理(本demo中采用的是修改targetSDKVersion=22)

三、使用方法

本Demo搭配《AppDir【创建缓存目录】》使用

package com.why.project.bitmaputildemo;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.why.project.bitmaputildemo.utils.AppDir;
import com.why.project.bitmaputildemo.utils.BitmapUtil;
import com.why.project.bitmaputildemo.utils.FileUtils;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private ImageView img_source;
    private ImageView img_scale1;
    private ImageView img_scale2;

    private Button btn_save;
    private Button btn_show;
    private ImageView img_show;

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

        initViews();
        initDatas();
        initEvents();
    }

    private void initViews() {
        img_source = (ImageView) findViewById(R.id.img_source);
        img_scale1 = (ImageView) findViewById(R.id.img_scale1);
        img_scale2 = (ImageView) findViewById(R.id.img_scale2);

        btn_save = (Button) findViewById(R.id.btn_save);
        btn_show = (Button) findViewById(R.id.btn_show);
        img_show = (ImageView) findViewById(R.id.img_show);
    }

    private void initDatas() {
        img_source.setImageResource(R.mipmap.ic_launcher);

        Bitmap sourceBitmap = BitmapUtil.drawableToBitmap(getResources().getDrawable(R.mipmap.ic_launcher));
        Bitmap sacleBitmap1 = BitmapUtil.bitmapZoomByHeight(sourceBitmap,200);
        img_scale1.setImageBitmap(sacleBitmap1);

        Bitmap sacleBitmap2 = BitmapUtil.bitmapZoomByScale(sourceBitmap,2,1);
        img_scale2.setImageBitmap(sacleBitmap2);
    }

    private void initEvents() {
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pngFilePath = AppDir.getInstance(MainActivity.this).IMAGE + File.separator + System.currentTimeMillis() + ".png";
                Bitmap sourceBitmap = BitmapUtil.drawableToBitmap(getResources().getDrawable(R.mipmap.ic_launcher));
                BitmapUtil.saveBitmapToSDCard(sourceBitmap,pngFilePath);
            }
        });

        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pngPath = FileUtils.firstFile(AppDir.getInstance(MainActivity.this).IMAGE);
                Bitmap pngBitmap = BitmapUtil.getBitmapFromSDCard(pngPath);
                img_show.setImageBitmap(pngBitmap);
            }
        });
    }
}

混淆配置

参考资料

暂时空缺

项目demo下载地址

https://github.com/haiyuKing/BitmapUtilDemo

BitmapUtil【缩放bitmap以及将bitmap保存成图片到SD卡中】

原文:http://www.cnblogs.com/whycxb/p/7635940.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!