举例说明Bitmap的用法

本文介绍如何在Android程序中引用存储卡上的图片文件,并通过Bitmap对象进行图片处理,包括显示和旋转。通过实例展示了从文件路径加载图片到ImageView的方法,以及使用Matrix类实现图像旋转的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般在android程序中把图片文件放在res/drawable目录下就可以通过R.drawable.id来使用,但在存储卡中的图片怎样引用呢?下面通过实现这个功能来介绍Bitmap的用法。

程序如下:

import java.io.File;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class A10Activity extends Activity {
 private Button b;
 private ImageView iv;
 private TextView tv;
 private String fileName="sdcard/picture/红叶.jpg";
 //private String fileName="sdcard/picture/红叶.jpg";这种写法是错误的,路径不是以

//设备开头
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b=(Button)findViewById(R.id.button);
        b.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    iv=(ImageView)findViewById(R.id.imageview);
    tv=(TextView)findViewById(R.id.textview);
    File f=new File(fileName);

//先判断图片文件是否存在
    if(f.exists()){

//如果存在,通过Bitmap将图片放入ImageView中显示出来

/*BitmapFactory(Android.graphics.BitmapFactory)是Android API提供的对象,该对象

*的decodeFile()方法将手机中的图片文件转换成Bitmap对象。*/
     Bitmap bm=BitmapFactory.decodeFile(fileName);
     iv.setImageBitmap(bm);
     tv.setText(fileName);
    }
    else{
     tv.setText("文件不存在");
    }
   }
         
        });
    }
}

 

BitmapFactory也提供了其他方法,例如decodeResource()可以将res/drawable内预先存入的图片文件转换成Bitmap对象,decodeStream()方法可将InputStream转化成Bitmap对象。

 

 

下面这个例子是利用Matrix.setRotate()方法来实现ImageView的旋转。原理是将ImageView放入Bitmap中,然后利用Bitmap.createBitmap()方法来创建新的Bitmap对象,在创建的同时,Matrix对象里的setRotate()方法动态旋转新创建的Bitmap.然后将旋转好的Bitmap对象以新构造的方式创建新的Bitmap,并将其放入原来的ImageView中。

 

程序如下所示:

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class A11Activity extends Activity {
 private ImageView iv;
 private TextView tv;
 private Button left,right; 
 private int times;
 private int angle;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        times=1;
        angle=1;
        iv=(ImageView)findViewById(R.id.iv);
        tv=(TextView)findViewById(R.id.tv);
        left=(Button)findViewById(R.id.left);
        left.setText("向左转");       
        right=(Button)findViewById(R.id.right);
        right.setText("向右转");
        final Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.a);  //自己引入一张图片a.png
        final int width=bmp.getWidth();
        final int height=bmp.getHeight();
        iv.setImageBitmap(bmp);
        left.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    angle--;
    if(angle<-20){    //设置最多旋转20度
     angle=-20;
    }
    int width01=width*times;
    int height01=height*times;
    float width02=(float)(width01/width);
    float height02=(float)(width02/height);
    Matrix m=new Matrix();
    m.postScale(width02, height02);
    m.setRotate(5*angle);
    Bitmap bmp01=Bitmap.createBitmap(bmp, 0, 0, width, height, m, true);
    BitmapDrawable bd=new BitmapDrawable(bmp01);
    iv.setImageDrawable(bd);
    tv.setText(Integer.toString(5*angle));
   }
         
        });
        right.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    angle++;
    if(angle>20){
     angle=20;
    }
    int width01=width*times;
    int height01=height*times;
    float width02=(float)(width01/width);
    float height02=(float)(width02/height);
    Matrix m=new Matrix();
    m.postScale(width02, height02);
    m.setRotate(5*angle);
    Bitmap bmp01=Bitmap.createBitmap(bmp, 0, 0, width, height, m, true);
    BitmapDrawable bd=new BitmapDrawable(bmp01);
    iv.setImageDrawable(bd);
    tv.setText(Integer.toString(5*angle));
   }
         
        });
    }
}

res/layout/main.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <Button
        android:id="@+id/left"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <Button
        android:id="@+id/right"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <ImageView
        android:id="@+id/iv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>

 

 

 

 

android Bitmap用法总结 Bitmap用法总结 1、Drawable → Bitmap public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap .createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); // canvas.setBitmap(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } 2、从资源中获取Bitmap Resources res=getResources(); Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic); 3、Bitmap → byte[] private byte[] Bitmap2Bytes(Bitmap bm){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } 4、byte[] → Bitmap private Bitmap Bytes2Bimap(byte[] b){ if(b.length!=0){ return BitmapFactory.decodeByteArray(b, 0, b.length); } else { return null; } } 5、保存bitmap static boolean saveBitmap2file(Bitmap bmp,String filename){ CompressFormat format= Bitmap.CompressFormat.JPEG; int quality = 100; OutputStream stream = null; try { stream = new FileOutputStream("/sdcard/" + filename); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. e.printStackTrace(); } return bmp.compress(format, quality, stream); } 6、将图片按自己的要求缩放 // 图片源 Bitmap bm = BitmapFactory.decodeStream(getResources() .openRawResource(R.drawable.dog)); // 获得图片的宽高 int width = bm.getWidth(); int height = bm.getHeight(); // 设置想要的大小 int newWidth = 320; int newHeight = 480; // 计算缩放比例 float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // 取得想要缩放的matrix参数 Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); // 得到新的图片 Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true); // 放在画布上 canvas.drawBitmap(newbm, 0, 0, paint); 相关知识链接:http://www.eoeandroid.com/thread-3162-1-1.html 7、bitmap用法小结 BitmapFactory.Options option = new BitmapFactory.Options(); option.inSampleSize = 2; //将图片设为原来宽高的1/2,防止内存溢出 Bitmap bm = BitmapFactory.decodeFile("",option);//文件流 URL url = new URL(""); InputStream is = url.openStream(); Bitmap bm = BitmapFactory.decodeStream(is); android:scaleType: android:scaleType是控制图片如何resized/moved来匹对ImageView的size。ImageView.ScaleType / android:scaleType值的意义区别: CENTER /center 按图片的原来size居中显示,当图片长/宽超过View的长/宽,则截取图片的居中部分 显示 CENTER_CROP / centerCrop 按比例扩大图片的size居中显示,使得图片长(宽)等于或大于View的长 (宽) CENTER_INSIDE / centerInside 将图片的内容完整居中显示,通过按比例缩小或原来的size使得图片 长/宽等于或小于View的长/宽 Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. FIT_CENTER / fitCenter 把图片按比例扩大/缩小到View的宽度,居中显示 FIT_END / fitEnd 把图片按比例扩大/缩小到View的宽度,显示在View的下部分位置 FIT_START / fitStart 把图片按比例扩大/缩小到View的宽度,显示在View的上部分位置 FIT_XY / fitXY 把图片 不按比例 扩大/缩小到View的大小显示 MATRIX / matrix 用矩阵来绘制,动态缩小放大图片来显示。 //放大缩小图片 public static Bitmap zoomBitmap(Bitmap bitmap,int w,int h){ int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidht = ((float)w / width); float scaleHeight = ((float)h / height); matrix.postScale(scaleWidht, scaleHeight); Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); return newbmp; } //将Drawable转化为Bitmap public static Bitmap drawableToBitmap(Drawable drawable){ int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0,0,width,height); drawable.draw(canvas); return bitmap; Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. } //获得圆角图片的方法 public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx){ Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap .getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } //获得带倒影的图片方法 public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap){ final int reflectionGap = 4; int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height/2, width, height/2, matrix, false); Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height/2), Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(bitmap, 0, 0, null); Paint deafalutPaint = new Paint(); Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. canvas.drawRect(0, height,width,height + reflectionGap, deafalutPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); paint.setShader(shader); // Set the Transfer mode to be porter duff and destination in paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); // Draw a rectangle using the paint with our linear gradient canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); return bitmapWithReflection; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值