Android-Bitmap详解

Android技术精髓-Bitmap详解



Bitmap (android.graphics.Bitmap)

Bitmap是Android系统中的图像处理的最重要类之一。用它可以获取图像文件信息,进行图像剪切、旋转、缩放等操作,并可以指定格式保存图像文件。

Bitmap类:

public boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream)    压缩:

将位图的压缩到指定的OutputStream。如果返回true,位图可以通过传递一个相应的InputStream BitmapFactory.decodeStream(重建)。
format: 压缩图像的格式 
quality: 0-100。 0含义压缩为小尺寸,100压缩的意思为最大质量。(PNG是无损的,会忽略品质设定 )
stream: OutputStream中写入压缩数据。
return: 是否成功压缩到指定的流。


public void recycle()——回收位图占用的内存空间,把位图标记为Dead 

public final boolean isRecycled() ——
判断位图内存是否已释放 

public final int getWidth()——
获取位图的宽度 

public final int getHeight()——
获取位图的高度 

public final boolean isMutable()——
图片是否可修改 

public int getScaledWidth(Canvas canvas)——
获取指定密度转换后的图像的宽度 

public int getScaledHeight(Canvas canvas)——
获取指定密度转换后的图像的高度 

public boolean compress(CompressFormat format, int quality, OutputStreamstream)——
按指定的图片格式以及画质,将图片转换为输出流。

format
Bitmap.CompressFormat.PNGBitmap.CompressFormat.JPEG 

quality
:画质,0-100.0表示最低画质压缩,100以最高画质压缩。对于PNG等无损格式的图片,会忽略此项设置。

常用的静态方法:

public staticBitmap createBitmap(Bitmap src) ——以src为原图生成不可变得新图像
public staticBitmap createScaledBitmap(Bitmap src, int dstWidth,
            int dstHeight, boolean filter)——以src为原图,创建新的图像,指定新图像的高宽以及是否变。
public staticBitmap createBitmap(int width, int height, Config config)——创建指定格式、大小的位图
public staticBitmap createBitmap(Bitmap source, int x, int y, int width, int height)source为原图,创建新的图片,指定起始坐标以及新图像的高宽。
public staticBitmap createBitmap(Bitmap source, int x, int y, int width, int height, Matrixm, boolean filter)


BitmapFactory工厂类:

Option 参数类:
public boolean inJustDecodeBounds——如果设置为true,不获取图片,不分配内存,但会返回图片的高宽度信息。

public int inSampleSize——图片缩放的倍数。如果设为4,则宽和高都为原来的1/4,则图是原来的1/16

public int outWidth——获取图片的宽度值

public int outHeight——获取图片的高度值

public int inDensity——用于位图的像素压缩比

public int inTargetDensity——用于目标位图的像素压缩比(要生成的位图)

public boolean inScaled——设置为true时进行图片压缩,从inDensityinTargetDensity
读取一个文件路径得到一个位图。如果指定文件为空或者不能解码成文件,则返回NULL

public staticBitmap decodeFile(String pathName, Options opts)

public staticBitmap decodeFile(String pathName)
读取一个资源文件得到一个位图。如果位图数据不能被解码,或者opts参数只请求大小信息时,则返回NuLL。(即当Options.inJustDecodeBounds=true,只请求图片的大小信息。)

public staticBitmap decodeResource(Resources res, int id)
public staticBitmap decodeResource(Resources res, int id, Options opts)

从输入流中解码位图
public static Bitmap decodeStream(InputStreamis)

从字节数组中解码生成不可变的位图
public staticBitmap decodeByteArray(byte[] data, int offset, int length)

BitmapDrawable类:
继承于Drawable,你可以从文件路径、输入流、XML文件以及Bitmap中创建。

常用的构造函数:
Resourcesres=getResources();//获取资源

publicBitmapDrawable(Resources res)——创建一个空的drawable。(Response用来指定初始时所用的像素密度)替代public BitmapDrawable()方法(此方法不处理像素密度)

publicBitmapDrawable(Resources res, Bitmap bitmap)——从位图创建绘制

publicBitmapDrawable(Resources res, String filepath)——通过打开agiven文件路径和位图解码创建绘制

publicBitmapDrawable(Resources res, java.io.InputStream is)——创建一个可绘制从给定的输入流bydecoding位图。



使用BitmapFactory解码资源


<span style="font-family:Microsoft YaHei;">import android.app.Activity;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;

public class Test extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
          ImageView imgView = (ImageView)findViewById(R.id.image3);
          
          imgView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.icon) );
      }
}
</span>

//main.xml
<span style="font-family:Microsoft YaHei;"><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"  android:layout_height="fill_parent">
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"  android:layout_height="fill_parent">

  <ImageView android:id="@+id/image1"
    android:layout_width="wrap_content"  android:layout_height="wrap_content"
    android:src="@drawable/icon"
    />

  <ImageView android:id="@+id/image2"
    android:layout_width="125dip"  android:layout_height="25dip"
    android:src="#555555"
    />
  </LinearLayout>
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"  android:layout_height="fill_parent">

  <ImageView android:id="@+id/image3"
    android:layout_width="wrap_content"  android:layout_height="wrap_content"
    />

  <ImageView android:id="@+id/image4"
    android:layout_width="wrap_content"  android:layout_height="wrap_content"
    android:src="@drawable/icon"
    android:scaleType="centerInside"
    android:maxWidth="35dip"  android:maxHeight="50dip"
    />

  </LinearLayout>
</LinearLayout></span>




捕获和保存位图

<span style="font-family:Microsoft YaHei;">import java.io.File;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.View;

public class Test extends Activity {
  Uri myPicture = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
    public void captureImage(View view)
    {
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(i, 0);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==0 && resultCode==Activity.RESULT_OK)
        {
             Bitmap myBitmap = (Bitmap) data.getExtras().get("data");
        }
    }
}
</span>


位图大小 

<span style="font-family:Microsoft YaHei;">import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.widget.ImageView;

public class Test extends Activity {
  final static int CAMERA_RESULT = 0;
  ImageView imv;
  String imageFilePath;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/a.jpg";
    File imageFile = new File(imageFilePath);
    Uri imageFileUri = Uri.fromFile(imageFile);
    Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
    startActivityForResult(i, CAMERA_RESULT);
  }

  protected void onActivityResult(int requestCode, int resultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    if (resultCode == RESULT_OK) {
      imv = (ImageView) findViewById(R.id.ReturnedImageView);
      Display currentDisplay = getWindowManager().getDefaultDisplay();
      BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
      bmpFactoryOptions.inJustDecodeBounds = true;
      Bitmap bmp = BitmapFactory.decodeFile(imageFilePath,
          bmpFactoryOptions);

      bmpFactoryOptions.inSampleSize = 2;
      bmpFactoryOptions.inJustDecodeBounds = false;
      bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
      imv.setImageBitmap(bmp);
    }
  }
}</span>

//layout/main.xml
<span style="font-family:Microsoft YaHei;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <ImageView android:id="@+id/ReturnedImageView" 
             android:layout_width="wrap_content" 
             android:layout_height="wrap_content"></ImageView>
</LinearLayout>
</span>


在画布(Canvas)上绘制位图

<span style="font-family:Microsoft YaHei;">import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Test extends Activity implements OnClickListener {
  ImageView chosenImageView;
  Button choosePicture;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    chosenImageView = (ImageView) this.findViewById(R.id.ChosenImageView);
    choosePicture = (Button) this.findViewById(R.id.ChoosePictureButton);

    choosePicture.setOnClickListener(this);
  }

  public void onClick(View v) {
    Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(choosePictureIntent, 0);
  }

  protected void onActivityResult(int requestCode, int resultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (resultCode == RESULT_OK) {
      Uri imageFileUri = intent.getData();
      try {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
                imageFileUri), null, bmpFactoryOptions);
        bmpFactoryOptions.inSampleSize = 2;

        bmpFactoryOptions.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
                imageFileUri), null, bmpFactoryOptions);
        Bitmap alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp
            .getHeight(), bmp.getConfig());
        Canvas canvas = new Canvas(alteredBitmap);
        Paint paint = new Paint();
        canvas.drawBitmap(bmp, 0, 0, paint);
        ImageView alteredImageView = (ImageView) this
            .findViewById(R.id.AlteredImageView);
        alteredImageView.setImageBitmap(alteredBitmap);
        chosenImageView.setImageBitmap(bmp);
      } catch (FileNotFoundException e) {
        Log.v("ERROR", e.toString());
      }
    }
  }
}</span>

//main.xml
<span style="font-family:Microsoft YaHei;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Choose Picture" android:id="@+id/ChoosePictureButton"/>

<ImageView android:layout_width="wrap_content" 
           android:layout_height="wrap_content" 
           android:id="@+id/ChosenImageView"></ImageView>
<ImageView android:layout_width="wrap_content" 
           android:layout_height="wrap_content" 
           android:id="@+id/AlteredImageView"></ImageView>
</LinearLayout></span>




Bitmap.createBitmap
<span style="font-family:Microsoft YaHei;">import java.io.FileNotFoundException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Test extends Activity implements OnClickListener {
  Button choosePicture1, choosePicture2;
  ImageView compositeImageView;
  Bitmap bmp1, bmp2;
  Canvas canvas;
  Paint paint;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    compositeImageView = (ImageView) this
        .findViewById(R.id.CompositeImageView);

    choosePicture1 = (Button) this.findViewById(R.id.ChoosePictureButton1);
    choosePicture2 = (Button) this.findViewById(R.id.ChoosePictureButton2);

    choosePicture1.setOnClickListener(this);
    choosePicture2.setOnClickListener(this);
  }

  public void onClick(View v) {
    Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(choosePictureIntent, 1);
  }

  protected void onActivityResult(int requestCode, int resultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (resultCode == RESULT_OK) {
      Uri imageFileUri = intent.getData();
      bmp1 = loadBitmap(imageFileUri);
      Bitmap drawingBitmap = Bitmap.createBitmap(bmp1.getWidth(),
          bmp1.getHeight(), bmp1.getConfig());
      canvas = new Canvas(drawingBitmap);
      paint = new Paint();
      canvas.drawBitmap(bmp1, 0, 0, paint);
      paint.setXfermode(new PorterDuffXfermode(
          android.graphics.PorterDuff.Mode.MULTIPLY));
      canvas.drawBitmap(bmp2, 0, 0, paint);
      compositeImageView.setImageBitmap(drawingBitmap);
    }
  }

  private Bitmap loadBitmap(Uri imageFileUri) {
    Display currentDisplay = getWindowManager().getDefaultDisplay();

    float dw = currentDisplay.getWidth();
    float dh = currentDisplay.getHeight();

    Bitmap returnBmp = Bitmap.createBitmap((int) dw, (int) dh,
        Bitmap.Config.ARGB_4444);
    try {
      BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
      bmpFactoryOptions.inJustDecodeBounds = true;
      returnBmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
      bmpFactoryOptions.inSampleSize = 2;
      bmpFactoryOptions.inJustDecodeBounds = false;
      returnBmp = BitmapFactory.decodeStream(getContentResolver()
          .openInputStream(imageFileUri), null, bmpFactoryOptions);
    } catch (Exception e) {
      Log.v("ERROR", e.toString());
    }
    return returnBmp;
  }
}
</span>


在画布上绘制位图(使用矩阵)
<span style="font-family:Microsoft YaHei;">import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Test extends Activity implements OnClickListener {

  ImageView chosenImageView;
  Button choosePicture;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    chosenImageView = (ImageView) this.findViewById(R.id.ChosenImageView);
    choosePicture = (Button) this.findViewById(R.id.ChoosePictureButton);

    choosePicture.setOnClickListener(this);
  }

  public void onClick(View v) {
    Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(choosePictureIntent, 0);
  }

  protected void onActivityResult(int requestCode, int resultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (resultCode == RESULT_OK) {
      Uri imageFileUri = intent.getData();

      Display currentDisplay = getWindowManager().getDefaultDisplay();
      int dw = currentDisplay.getWidth();
      int dh = currentDisplay.getHeight() / 2 - 100;
      try {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
                imageFileUri), null, bmpFactoryOptions);

        bmpFactoryOptions.inSampleSize = 2;

        bmpFactoryOptions.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(
                imageFileUri), null, bmpFactoryOptions);

        Bitmap alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp
            .getHeight(), bmp.getConfig());
        Canvas canvas = new Canvas(alteredBitmap);
        Paint paint = new Paint();
        canvas.drawBitmap(bmp, 0, 0, paint);
        Matrix matrix = new Matrix();
        matrix.setValues(new float[] { 1, .5f, 0, 0, 1, 0, 0, 0, 1 });
        canvas.drawBitmap(bmp, matrix, paint);

        ImageView alteredImageView = (ImageView) this.findViewById(R.id.AlteredImageView);
        alteredImageView.setImageBitmap(alteredBitmap);

        chosenImageView.setImageBitmap(bmp);

      } catch (Exception e) {
        Log.v("ERROR", e.toString());
      }
    }
  }
}</span>


//main.xml

<span style="font-family:Microsoft YaHei;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Choose Picture" android:id="@+id/ChoosePictureButton"/>

<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ChosenImageView"></ImageView>
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/AlteredImageView"></ImageView>
</LinearLayout>
</span>


创建一个位图来画

<span style="font-family:Microsoft YaHei;">import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.ImageView;

public class Test extends Activity {
  ImageView drawingImageView;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    drawingImageView = (ImageView) this.findViewById(R.id.DrawingImageView);
    Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
        .getDefaultDisplay().getWidth(), (int) getWindowManager()
        .getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawingImageView.setImageBitmap(bitmap);

    Paint paint = new Paint();
    paint.setColor(Color.GREEN);
    paint.setTextSize(20);
    paint.setTypeface(Typeface.DEFAULT);
    Path p = new Path();
    p.moveTo(20, 20);
    p.lineTo(100, 150);
    p.lineTo(200, 220);
    canvas.drawTextOnPath("this is a test", p, 0, 0, paint);
  }
}
</span>



加载位图和画
<span style="font-family:Microsoft YaHei;">import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class Test extends Activity {
  class RenderView extends View {
    Bitmap bitmap1;
    Bitmap bitmap2;
    Rect dst = new Rect();

    public RenderView(Context context) {
      super(context);
      try {
        AssetManager assetManager = context.getAssets();
        InputStream inputStream = assetManager.open("a.png");
        bitmap1 = BitmapFactory.decodeStream(inputStream);
        inputStream.close();
        Log.d("Text",""+bitmap1.getConfig());
        inputStream = assetManager.open("b.png");
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_4444;
        bitmap2 = BitmapFactory.decodeStream(inputStream, null, options);
        inputStream.close();
        Log.d("BitmapText","" + bitmap2.getConfig());
      } catch (IOException e) {
        
      }
    }

    protected void onDraw(Canvas canvas) {
      dst.set(50, 50, 350, 350);
      canvas.drawBitmap(bitmap1, null, dst, null);
      canvas.drawBitmap(bitmap2, 100, 100, null);
      invalidate();
    }
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(new RenderView(this));
  }
}
</span>



总结一下:

1. 从资源中获取位图
可以使用BitmapDrawable或者BitmapFactory来获取资源中的位图。
当然,首先需要获取资源: Resources res=getResources();
使用BitmapDrawable获取位图
    1. 使用BitmapDrawable (InputStream is)构造一个BitmapDrawable
    2. 使用BitmapDrawable类的getBitmap()获取得到位图;
通过Resource的函数:InputStream openRawResource(int id)获取得到资源文件的数据流后,也可以通2种方法来获取Bitmap,如下:
使用BitmapDrawable
A Drawable that wraps a bitmap and can be tiled,stretched, or aligned.
使用BitmapDrawable (InputStream is)构造一个BitmapDrawable
使用BitmapDrawable类的getBitmap()获取得到位图;
BitmapDrawable也提供了显示位图等操作。
InputStreamis=res.openRawResource(R.drawable.pic180); // 读取资源文件获取输入流
BitmapDrawablebmpDraw=new BitmapDrawable(is);   
Bitmapbmp=bmpDraw.getBitmap();
或者:
BitmapDrawablebmpDraw=(BitmapDrawable)res.getDrawable(R.drawable.pic180);   
Bitmapbmp=bmpDraw.getBitmap();
使用BitmapFactory
Creates Bitmap objects from various sources, includingfiles, streams, and byte-arrays.
使用BitmapFactorydecodeStream(InputStream is)解码位图资源,获取位图。
使用BitmapFactoryBitmap bmp=BitmapFactory.decodeResource(res,R.drawable.pic180); 方法解码位图资源。
BitmapFactory的所有函数都是static,这个辅助类可以通过资源ID、路径、文件、数据流等方式来获取位图。
以上方法在编程的时候可以自由选择,在Android SDK中说明可以支持的图片格式如下:png (preferred), jpg (acceptable), gif(discouraged),虽然bmp格式没有明确说明,但是在Android SDK Support Media Format中是明确说明了。

2. 获取位图的信息
要获取位图信息,比如位图大小、是否包含透明度、颜色格式等,获取得到Bitmap就迎刃而解了,这些信息在Bitmap的函数中可以轻松获取到。Android SDK中对Bitmap有详细说明,阅读起来也比较容易,不在此详细说明,这里只是辅助说明以下2点:
Bitmap中对RGB颜色格式使用Bitmap.Config定义,仅包括ALPHA_8ARGB_4444ARGB_8888RGB_565,缺少了一些其他的,比如说RGB_555,在开发中可能需要注意这个小问题;
Bitmap还提供了compress()接口来压缩图片,不过AndroidSAK只支持PNGJPG格式的压缩;其他格式的需要Android开发人员自己补充了。

3. 显示位图
显示位图可以使用核心类Canvas,通过Canvas类的drawBirmap()显示位图,或者借助于BitmapDrawable来将Bitmap绘制到Canvas。当然,也可以通过BitmapDrawable将位图显示到View中。
转换为BitmapDrawable对象显示位图
         //获取位图
        Bitmapbmp=BitmapFactory.decodeResource(res, R.drawable.pic180);
        // 转换为BitmapDrawable对象
        BitmapDrawable bmpDraw=newBitmapDrawable(bmp);
        // 显示位图
        ImageView iv2 =(ImageView)findViewById(R.id.ImageView02);
       iv2.setImageDrawable(bmpDraw);
使用Canvas类显示位图
这儿采用一个继承自View的子类Panel,在子类的OnDraw中显示
Java代码
public classMainActivity extends Activity {   
     
    @Override
    public void onCreate(BundlesavedInstanceState) {   
       super.onCreate(savedInstanceState);  
        setContentView(new Panel(this));   
    }   
      
    class Panel extends View{            
        public Panel(Context context) {     
            super(context);   
        }         
        public void onDraw(Canvas canvas){     
            Bitmap bmp =BitmapFactory.decodeResource(getResources(), R.drawable.pic180);   
            canvas.drawColor(Color.BLACK);   
            canvas.drawBitmap(bmp, 10, 10,null);     
        }   
    }   
}  

4. 位图缩放
1)将一个位图按照需求重画一遍,画后的位图就是我们需要的了,与位图的显示几乎一样:drawBitmap(Bitmap bitmap, Rect src, Rect dst,Paint paint)
2)在原有位图的基础上,缩放原位图,创建一个新的位图:CreateBitmap(Bitmap source, int x, int y,int width, int height, Matrix m, boolean filter)
3)借助Canvasscale(float sx, float sy) Preconcat the current matrix with thespecified scale.),不过要注意此时整个画布都缩放了。
4)借助Matrix
Bitmap bmp =BitmapFactory.decodeResource(getResources(), R.drawable.pic180);   
Matrix matrix=new Matrix();   
matrix.postScale(0.2f,0.2f);   
Bitmapdstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),
bmp.getHeight(),matrix,true);   
canvas.drawColor(Color.BLACK);     
canvas.drawBitmap(dstbmp,10, 10, null);   

5. 位图旋转
同样,位图的旋转也可以借助Matrix或者Canvas来实现。Matrix在线性代数中都学习过,Android SDK提供了Matrix类,可以通过各种接口来设置矩阵。结合上面的例子程序,将位图缩放例子程序在显示位图的时候前,增加位图旋转功能,修改代码如下:
Matrix matrix = new Matrix();
//matrix.postScale(0.5f,0.5f);
matrix.setRotate(90,120,130);
canvas.drawBitmap(mbmpTest,matrix, mPaint);
除了这种方法之外,我们也可以在使用Bitmap提供的函数如下:
public staticBitmap createBitmap (Bitmap source, int x, int y, int width, int height, Matrixm, boolean filter),在原有位图旋转的基础上,创建新位图。


2014.2.5

你可能感兴趣的:(java,android,bitmap,内存,图像处理)