Bitmap是Android系统中的图像处理的最重要类之一。用它可以获取图像文件信息,进行图像剪切、旋转、缩放等操作,并可以指定格式保存图像文件。本文从应用的角度,着重介绍怎么用Bitmap来实现这些功能。
一、Bitmap的生成
1.1 BitmapFactory decode出Bitmap
Bitmap实现在android.graphics包中。但是Bitmap类的构造函数是私有的,外面并不能实例化,只能是通过JNI实例化。这必然是 某个辅助类提供了创建Bitmap的接口,而这个类的实现通过JNI接口来实例化Bitmap的,这个类就是BitmapFactory。

图一、BitmapFactory主要方法及Options选项
利用BitmapFactory可以从一个指定文件中,利用decodeFile()解出Bitmap;也可以定义的图片资源中,利用decodeResource()解出Bitmap。
1.2 decode时的选项
在使用方法decodeFile()/decodeResource()时,都可以指定一个BitmapFacotry.Options。
利用Options的下列属性,可以指定decode的选项:
- inPreferredConfig 指定decode到内存中,手机中所采用的编码,可选值定义在Bitmap.Config中。缺省值是ARGB_8888。
- inJustDecodeBounds 如果设置为true,并不会把图像的数据完全解码,亦即decodeXyz()返回值为null,但是Options的outAbc中解出了图像的基本信息。
- inSampleSize 设置decode时的缩放比例。
利用Options的这些值就可以高效的得到一幅缩略图。

图二、BitmapFactory.decodeFile()
先设置inJustDecodeBounds= true,调用decodeFile()得到图像的基本信息[Step#2~4];
利用图像的宽度(或者高度,或综合)以及目标的宽度,得到inSampleSize值,再设置inJustDecodeBounds= false,调用decodeFile()得到完整的图像数据[Step#5~8]。
先获取比例,再读入数据,如果欲读入大比例缩小的图,将显著的节约内容资源。有时候还会读入大量的缩略图,这效果就更明显了。
二、利用Bitmap和Matrix实现图像变换
Bitmap可以和Matrix结合实现图像的剪切、旋转、缩放等操作。

图三、Bitmap方法
用源Bitmap通过变换生成新的Bitmap的方法:
1 | public static Bitmap createBitmap(Bitmap source, int x, int y, intwidth, int height, |
2 | Matrix m, boolean filter) |
3 | public static Bitmap createBitmap(Bitmap source, int x, int y, intwidth, int height) |
4 | public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, |
5 | int dstHeight, boolean filter) |
第一个方法是最终的实现,后两种只是对第一种方法的封装。
第二个方法可以从源Bitmap中指定区域(x,y, width, height)中挖出一块来实现剪切;第三个方法可以把源Bitmap缩放为dstWidth x dstHeight的Bitmap。
设置Matrix的Rotate(通过setRotate())或者Scale(通过setScale()),传入第一个方法,可实现旋转或缩放。

图四、Bitmap实现旋转
三、保存图像文件
经过图像变换之后的Bitmap里的数据可以保存到图像压缩文件里(JPG/PNG)。

图五、保存Bitmap数据到文件
这个操作过程中,Bitmap.compress()方法的参数format可设置JPEG或PNG格式;quality可选择压缩质量;fOut是输出流(OutputStream),这里的FileOutputStream是OutputStream的一个子类。
总结一下,本文介绍Bitmap的使用方法——用Bitmap实现图像文件的读取和写入,并用Bitmap实现图像的剪切、旋转和缩放变换。
=================================================================================================================================
android 实现图片的翻转
1 | Resources res = this .getContext().getResources(); |
2 | img = BitmapFactory.decodeResource(res, R.drawable.aa); |
3 | Matrix matrix = new Matrix(); |
4 | matrix.postRotate( 180 ); |
5 | int width = img.getWidth(); |
6 | int height = img.getHeight(); |
7 | img_a = Bitmap.createBitmap(img, 0 , 0 , width, height, matrix, true ); |
然后可以直接把img_a draw到画布上,canvas.drawBitmap(img_a, 10, 10, p);
Matrix 是一个处理翻转、缩放等图像效果的重要类
Matrix.postScale 可设置缩放比例,默认为1
**********************************************************************
android 实现图片的旋转
01 | public class ex04_22 extends Activity{ |
03 | private ImageView mImageView; |
04 | private Button btn1,btn2; |
05 | private TextView mTextView; |
06 | private AbsoluteLayout layout1; |
07 | private int ScaleTimes= 1 ,ScaleAngle= 1 ; |
09 | public void onCreate(Bundle savedInstanceState) { |
10 | super .onCreate(savedInstanceState); |
11 | setContentView(R.layout.main); |
12 | mImageView=(ImageView)findViewById(R.id.myImageView); |
13 | final Bitmap bmp=BitmapFactory.decodeResource( this .getResources(),R.drawable.ex04_22_1); |
14 | final int widthOrig=bmp.getWidth(); |
15 | final int heightOrig=bmp.getHeight(); |
16 | mImageView.setImageBitmap(bmp); |
17 | btn1=(Button)findViewById(R.id.myButton1); |
18 | btn1.setOnClickListener( new OnClickListener(){ |
19 | public void onClick(View v){ |
24 | int newWidth=widthOrig*ScaleTimes; |
25 | int newHeight=heightOrig*ScaleTimes; |
26 | float scaleWidth=(( float )newWidth)/widthOrig; |
27 | float scaleHeight=(( float )newHeight)/heightOrig; |
28 | Matrix matrix= new Matrix(); |
29 | matrix.postScale(scaleWidth, scaleHeight); |
30 | matrix.setRotate( 5 *ScaleAngle); |
31 | Bitmap resizeBitmap=Bitmap.createBitmap(bmp, 0 , 0 , widthOrig, heightOrig, matrix, true ); |
32 | BitmapDrawable myNewBitmapDrawable= new BitmapDrawable(resizeBitmap); |
33 | mImageView.setImageDrawable(myNewBitmapDrawable); |
36 | btn2=(Button)findViewById(R.id.myButton2); |
37 | btn2.setOnClickListener( new OnClickListener(){ |
38 | public void onClick(View v){ |
43 | int newWidth=widthOrig*ScaleTimes; |
44 | int newHeight=heightOrig*ScaleTimes; |
45 | float scaleWidth=(( float )newWidth)/widthOrig; |
46 | float scaleHeight=(( float )newHeight)/heightOrig; |
47 | Matrix matrix= new Matrix(); |
48 | matrix.postScale(scaleWidth, scaleHeight); |
49 | matrix.setRotate( 5 *ScaleAngle); |
50 | Bitmap resizeBitmap=Bitmap.createBitmap(bmp, 0 , 0 , widthOrig, heightOrig, matrix, true ); |
51 | BitmapDrawable myNewBitmapDrawable= new BitmapDrawable(resizeBitmap); |
52 | mImageView.setImageDrawable(myNewBitmapDrawable); |
**********************************************************************
实现画面淡入淡出效果可以用 :setAlpha(alpha);
alpha从255,逐渐递减!
**********************************************************************
如何实现屏幕的滚动效果,这里有两个关键点,一个是实现OnGestureListener,
以便在触摸事件发生的时候,被回调。包括按下,滚动等等,按照API文档,
需要分两步来实现检测手势行为。
1)创建GestureDetector实例
2) 在onTouchEvent()方法中调用GestureDetector的onTouchEvent()方法。
另一个关键点是自己实现一个简单的View,来绘制图片。
代码如下所示。由于,我们不需要使用layout定义,所以不需要提供xml文件。
直接在程序里面setContentView()即可。
003 | import android.app.Activity; |
004 | import android.content.Context; |
005 | import android.content.res.Resources; |
006 | import android.graphics.Bitmap; |
007 | import android.graphics.BitmapFactory; |
008 | import android.graphics.Canvas; |
009 | import android.graphics.Paint; |
010 | import android.os.Bundle; |
011 | import android.view.GestureDetector; |
012 | import android.view.MotionEvent; |
013 | import android.view.View; |
014 | import android.view.ViewGroup; |
015 | import android.view.GestureDetector.OnGestureListener; |
017 | public class HorizontalScroll extends Activity implements OnGestureListener { |
018 | private static final int X_MAX = 800 ; |
019 | private static final int Y_MAX = 600 ; |
020 | private int scrollX = 0 ; |
021 | private int scrollY = 0 ; |
028 | GestureDetector gestureScanner; |
031 | public void onCreate(Bundle savedInstanceState) { |
032 | super .onCreate(savedInstanceState); |
034 | gestureScanner = new GestureDetector( this ); |
038 | bmp = BitmapFactory.decodeResource(res, R.drawable.arc); |
039 | adapt = Bitmap.createBitmap(bmp); |
041 | main = new MyView( this ); |
042 | setContentView(main, new ViewGroup.LayoutParams( 800 , 600 )); |
046 | public boolean onTouchEvent(MotionEvent me) { |
047 | return gestureScanner.onTouchEvent(me); |
050 | public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, |
052 | main.handleScroll(distanceX, distanceY); |
056 | public boolean onDown(MotionEvent e) { |
060 | public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, |
065 | public void onLongPress(MotionEvent e) { |
068 | public void onShowPress(MotionEvent e) { |
071 | public boolean onSingleTapUp(MotionEvent e) { |
079 | class MyView extends View { |
080 | public MyView(Context context) { |
085 | protected void onDraw(Canvas canvas) { |
086 | canvas.drawBitmap(adapt, -scrollX, -scrollY, paint); |
089 | public void handleScroll( float distX, float distY) { |
096 | } else if (distX < - 6.0 ) { |
108 | } else if (distY < - 6.0 ) { |
**********************************************************************
教你在谷歌Android平台中处理图片
操作图像像素
现在你可以对单独的像素进行处理了。通过使用android.graphics.Bitmap API中的
getPixels,可以加载像素到一个整数数组中。在本文例子中,你将按照一定规则对每一
个像素实现着色。经过这个处理后,所有的像素将被转化为一个范围在0到255的字节码。
android.graphics.Bitmap API中的setPixels则用来加载这个整数数组到一个图像中。
最后一步是通过ImageView变量mIV来更新屏幕。以下是实现这个染色过程的代码片段。
01 | private void TintThePicture( int deg) { |
02 | int [] pix = new int [picw * pich]; |
03 | mBitmap.getPixels(pix, 0 , picw, 0 , 0 , picw, pich); |
05 | int RY, GY, BY, RYY, GYY, BYY, R, G, B, Y; |
06 | double angle = ( 3 .14159d * ( double )deg) / 180 .0d; |
07 | int S = ( int )( 256 .0d * Math.sin(angle)); |
08 | int C = ( int )( 256 .0d * Math.cos(angle)); |
10 | for ( int y = 0 ; y < pich; y++) |
11 | for ( int x = 0 ; x < picw; x++) |
13 | int index = y * picw + x; |
14 | int r = (pix[index] >> 16 ) & 0xff ; |
15 | int g = (pix[index] >> 8 ) & 0xff ; |
16 | int b = pix[index] & 0xff ; |
17 | RY = ( 70 * r - 59 * g - 11 * b) / 100 ; |
18 | GY = (- 30 * r + 41 * g - 11 * b) / 100 ; |
19 | BY = (- 30 * r - 59 * g + 89 * b) / 100 ; |
20 | Y = ( 30 * r + 59 * g + 11 * b) / 100 ; |
21 | RYY = (S * BY + C * RY) / 256 ; |
22 | BYY = (C * BY - S * RY) / 256 ; |
23 | GYY = (- 51 * RYY - 19 * BYY) / 100 ; |
25 | R = (R < 0 ) ? 0 : ((R > 255 ) ? 255 : R); |
27 | G = (G < 0 ) ? 0 : ((G > 255 ) ? 255 : G); |
29 | B = (B < 0 ) ? 0 : ((B > 255 ) ? 255 : B); |
30 | pix[index] = 0xff000000 | (R << 16 ) | (G << 8 ) | B; |
33 | Bitmap bm = Bitmap.createBitmap(picw, pich, false ); |
34 | bm.setPixels(pix, 0 , picw, 0 , 0 , picw, pich); |
37 | mIV.setImageBitmap(bm); |
**********************************************************************
android 图片的放大和缩小
01 | public class ex04_22 extends Activity{ |
02 | private ImageView mImageView; |
03 | private Button btn1,btn2; |
04 | private TextView mTextView; |
05 | private AbsoluteLayout layout1; |
08 | private int displayWidth,displayHeight; |
09 | private float scaleWidth= 1 ,scaleHeight= 1 ; |
10 | private final static String filename= "/data/data/ex04_22.lcs/ex04_22_2.png" ; |
12 | public void onCreate(Bundle savedInstanceState) { |
13 | super .onCreate(savedInstanceState); |
14 | setContentView(R.layout.main); |
16 | DisplayMetrics dm= new DisplayMetrics(); |
17 | getWindowManager().getDefaultDisplay().getMetrics(dm); |
18 | displayWidth=dm.widthPixels; |
19 | displayHeight=dm.heightPixels- 80 ; |
20 | bmp=BitmapFactory.decodeResource( this .getResources(),R.drawable.ex04_22_1); |
21 | layout1=(AbsoluteLayout)findViewById(R.id.layout1); |
22 | mImageView=(ImageView)findViewById(R.id.myImageView); |
23 | btn1=(Button)findViewById(R.id.myButton1); |
24 | btn1.setOnClickListener( new OnClickListener(){ |
25 | public void onClick(View v){ |
29 | btn2=(Button)findViewById(R.id.myButton2); |
30 | btn2.setOnClickListener( new OnClickListener(){ |
31 | public void onClick(View v){ |
38 | int bmpWidth=bmp.getWidth(); |
39 | int bmpHeight=bmp.getHeight(); |
43 | scaleWidth=( float )(scaleWidth*scale); |
44 | scaleHeight=( float )(scaleHeight*scale); |
46 | Matrix matrix= new Matrix(); |
47 | matrix.postScale(scaleWidth, scaleHeight); |
48 | Bitmap resizeBmp=Bitmap.createBitmap(bmp, 0 , 0 , bmpWidth, bmpHeight, matrix, true ); |
50 | layout1.removeView(mImageView); |
53 | layout1.removeView((ImageView)findViewById(id)); |
56 | ImageView imageView= new ImageView( this ); |
58 | imageView.setImageBitmap(resizeBmp); |
59 | layout1.addView(imageView); |
60 | setContentView(layout1); |
65 | int bmpWidth=bmp.getWidth(); |
66 | int bmpHeight=bmp.getHeight(); |
70 | scaleWidth=( float )(scaleWidth*scale); |
71 | scaleHeight=( float )(scaleHeight*scale); |
73 | Matrix matrix= new Matrix(); |
74 | matrix.postScale(scaleWidth, scaleHeight); |
75 | Bitmap resizeBmp=Bitmap.createBitmap(bmp, 0 , 0 , bmpWidth, bmpHeight, matrix, true ); |
77 | layout1.removeView(mImageView); |
80 | layout1.removeView((ImageView)findViewById(id)); |
83 | ImageView imageView= new ImageView( this ); |
85 | imageView.setImageBitmap(resizeBmp); |
86 | layout1.addView(imageView); |
87 | setContentView(layout1); |
88 | if (scaleWidth*scale*bmpWidth>displayWidth||scaleHeight*scale*scaleHeight>displayHeight){ |
89 | btn2.setEnabled( false ); |
xml文件
01 | <? xml version = "1.0" encoding = "utf-8" ?> |
04 | android:id = "@+id/layout1" |
05 | android:layout_width = "fill_parent" |
06 | android:layout_height = "fill_parent" |
07 | xmlns:android = "http://schemas.android.com/apk/res/android" |
10 | android:id = "@+id/myImageView" |
11 | android:layout_width = "200px" |
13 | android:layout_height = "150px" |
14 | android:src = "@drawable/ex04_22_1" |
20 | android:id = "@+id/myButton1" |
22 | android:layout_width = "90px" |
23 | android:layout_height = "60px" |
25 | android:textSize = "18sp" |
26 | android:layout_x = "20px" |
27 | android:layout_y = "372px" |
32 | android:id = "@+id/myButton2" |
33 | android:layout_width = "90px" |
34 | android:layout_height = "60px" |
36 | android:textSize = "18sp" |
38 | android:layout_x = "210px" |
39 | android:layout_y = "372px" |
*********************************************************************
android 图片透明度处理代码
01 | public static Bitmap setAlpha(Bitmap sourceImg, int number) { |
03 | int [] argb = new int [sourceImg.getWidth() * sourceImg.getHeight()]; |
05 | sourceImg.getPixels(argb, 0 , sourceImg.getWidth(), 0 , 0 ,sourceImg.getWidth(), sourceImg.getHeight()); |
07 | number = number * 255 / 100 ; |
09 | for ( int i = 0 ; i < argb.length; i++) { |
11 | argb = (number << 24 ) | (argb & 0x00FFFFFF ); |
15 | sourceImg = Bitmap.createBitmap(argb, sourceImg.getWidth(), sourceImg.getHeight(), Config.ARGB_8888); |
===================================================================================================================================
====================================================================================================================================
有一阵没更新了,不过项目也已经基本完成,可以写一部分新文章咯。项目虽然已经做完,但是问题还是不少,在3月份会有新的领导过来带领做新版,解决各种手机的适配及优化工作。
这回先讲一下ListView异步加载图片的问题,相关的文章很多,不过在这里我将加载、压缩下载、存储到SD卡等功能全部放上来,方便大家使用或者研究。
1. ListView中的SimpleAdapter中的操作
大家在使用ListView显示复杂的页面时,我们都全重写一个SimpleAdapter,重写其中的getView方法来显示具体内容。相关的内容我们下篇文章再说,这里主要看下图片显示的代码。
-
- if(!topic.getImage_value().equals("")){
- vh.tl_ll_content_image.setVisibility(View.VISIBLE);
-
- vh.tl_img_content_image.setTag(topic.getTid());
- vh.tl_img_content_image.setImageResource(R.drawable.default_image_load);
-
- LoadingTopicImageAsyncTaskloadingTopicImageAsyncTask = new LoadingTopicImageAsyncTask(vh.tl_img_content_image, topic,ctxContext,true,String.valueOf(topic.getTid()));
- loadingTopicImageAsyncTask.execute();
- }
·vh. tl_ll_content_image是我们在ListView中要显示相关图片的控件。Topic是我们通过getView取到的当前行的数据对象。Topic.getImage_value()中则是要显示的图片url地址,比如:http://www.huoban168.com/huoban/upload/topic/2012/02/weibo_1329196372_1112447.png。
·为图片控件加上setTag主要是防止图片混乱。
·LoadingTopicImageAsyncTask是我们新开一个异步,下载或者加载相关的图片的类。基本上主要的操作都在此类中进行。
2. LoadingTopicImageAsyncTask类中的操作
- packagehb.hbwb.asynctask;
- importhb.hbwb.model.beans.Topic;
- importhb.hbwb.tools.PicTool;
- importhb.hbwb.var.PublicVariable;
-
- importandroid.app.Activity;
- importandroid.app.Dialog;
- importandroid.graphics.Bitmap;
- importandroid.os.AsyncTask;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.ImageView;
-
-
-
-
-
-
-
-
-
-
- public classLoadingTopicImageAsyncTask extends
- AsyncTask<String, Integer,String> {
- private ImageView imageView = null;
- private Topic topic = null;
- private Bitmap bt = null;
- private Activity activity;
- private boolean isClick = true;
- private String tag = "";
-
-
-
-
-
-
-
-
-
-
-
- public LoadingTopicImageAsyncTask(ImageViewimageView, Topic topic,
- Activity activity, booleanisClick, String tag) {
- super();
- this.imageView = imageView;
- this.topic = topic;
- this.activity = activity;
- this.isClick = isClick;
- this.tag = tag;
- }
-
- @Override
- protected String doInBackground(String...params) {
-
- bt =PublicVariable.allTopicImage.get(String.valueOf(topic.getTid()));
- if (bt == null) {
-
- if (topic.getImage_value().equals("")){
- bt = null;
- } else {
- bt =PicTool.ReturnBitMap(topic.getImage_value());
- }
- }
- if (bt!=null) {
- if(bt.getWidth()>PublicVariable.TOPIC_IMAGE_SHOW-40 ||bt.getHeight()>PublicVariable.TOPIC_IMAGE_SHOW_HEIGHT-40) {
- bt =PicTool.ChangeSizeBitMap(bt, PublicVariable.TOPIC_IMAGE_SHOW-40);
- }
- }
- return null;
- }
-
- @Override
- protected void onPostExecute(String result) {
- super.onPostExecute(result);
- if (imageView != null &&topic != null && !tag.equals("")) {
- if(imageView.getTag().toString().equals(tag)) {
- if (bt != null) {
- if(isClick) {
-
- imageView.setOnClickListener(newOnClickListener() {
- @Override
- publicvoid onClick(View v) {
- ShowImageClickListener(bt,activity);
- }
- });
- }
- imageView.setImageBitmap(bt);
- PublicVariable.allTopicImage.put(
- String.valueOf(topic.getTid()),bt);
- }
- }
- }
- }
-
-
-
-
-
-
-
- public static voidShowImageClickListener(Bitmap bt, Activity activity) {
- Bitmap maxBt =PicTool.ChangeSizeBitMap(bt,
- PublicVariable.TOPIC_IMAGE_SHOW);
- ImageView showImageView = newImageView(activity);
- showImageView.setImageBitmap(maxBt);
-
-
- Dialog d = newDialog(activity.getParent(), hb.hbwb.R.style.no_back_title_dialog);
- d.setContentView(showImageView);
- d.setCanceledOnTouchOutside(true);
- d.show();
- }
-
- }
·PublicVariable.allTopicImage是我们写的一个HashMap,存储Bitmap的一个集合,如果在程序的运行过程中多次显示同一个图片即可直接从这里面取出Bitmap并显示,可以节省网上加载或者sd卡读取的步骤,键值是topic的tid,一个微博仅显示一张图片。
·如果上述的Bitmap集合中不存在图片的话,调用PicTool类中的ReturnBitMap返回SD卡上缓存的图片。
·如果图片超过我们规定的一个大小,那么调用PicTool类中的ChangeSizeBitMap方法。
·onPostExecute方法是线程执行完成后,我们将Bitmap对象给予Image图片控件并显示出来。在这里我们还添加了点击事件。
3. ReturnBitMap解析
-
-
-
-
-
-
-
- public static Bitmap ReturnBitMap(String url) {
- String imgName =StringTool.GetImageNameForUrl(url);
- if (imgName.equals("")) {
- return null;
- } else {
- FileTool ft = newFileTool();
- String path =FileFinals.SDCARDROOT + File.separator + FileFinals.SDCARDIMAGEPATH;
-
- if (ft.IsFileExist(imgName +FileFinals.IMAGE_SYSTEM_EXT, FileFinals.SDCARDIMAGEPATH)) {
- Bitmap bm =ReturnLocalBitMap(path + File.separator + imgName);
- if(bm==null){
- returnReturnWebBitMap(url, imgName, path);
- }else{
- returnbm;
- }
- } else {
-
- returnReturnWebBitMap(url, imgName, path);
- }
- }
- }
-
-
-
-
-
-
-
-
-
- public static Bitmap ReturnLocalBitMap(Stringpath) {
- Bitmap bitmap =BitmapFactory.decodeFile(path + ".image");
- return bitmap;
- }
-
-
-
-
-
-
-
-
-
-
-
-
- public static Bitmap ReturnWebBitMap(Stringurl, String imgName, String path) {
-
- Bitmap bitmap = null;
- try {
-
- InputStream size_is =HTMLTool.GetHttpConnection(url).getInputStream();
- BitmapFactory.Options op =new BitmapFactory.Options();
- op.inJustDecodeBounds =true;
- @SuppressWarnings("unused")
- Bitmap size_bitmap =BitmapFactory.decodeStream(size_is, null, op);
- op.inJustDecodeBounds =true;
- boolean isop = false;
- int size =PublicVariable.TOPIC_IMAGE_SHOW;
- int bili = 0;
- BitmapFactory.Options op_new= new BitmapFactory.Options();
- if(op.outWidth>op.outHeight){
- if (op.outWidth> size) {
- bili =op.outWidth / size;
- isop =true;
- }
- }else{
- if (op.outHeight> size) {
- bili =op.outHeight / size;
-
- isop =true;
- }
- }
-
-
- if (bili != 0) {
- if (bili < 2) {
- bili = 2;
- }else{
- bili = bili*2-2;
- }
- if(bili%2!=0){
- bili =bili+1;
- }
- op_new.inSampleSize= bili;
- } else {
- isop = false;
- }
- System.out.println(bili);
- size_bitmap = null;
- size_is.close();
-
-
- InputStream is =HTMLTool.GetHttpConnection(url).getInputStream();
- if (isop) {
- op_new.inPreferredConfig= Bitmap.Config.ARGB_4444;
- op_new.inPurgeable= true;
- op_new.inInputShareable= true;
- bitmap =BitmapFactory.decodeStream(is, null, op_new);
- } else {
- bitmap =BitmapFactory.decodeStream(is);
- }
-
-
-
- WriteBitmapToSdCard(FileFinals.SDCARDIMAGEPATH,path + File.separator + imgName, bitmap);
-
- is.close();
-
- } catch (Exception e) {
- return null;
- }
- return bitmap;
- }
·StringTool.GetImageNameForUrl是截取文件名,比如:http://www.huoban168.com/huoban/upload/topic/2012/02/weibo_1329196372_1112447.png,返回的是weibo_1329196372_1112447.png这一部分的内容。
·接下来查看当前SD卡的缓存文件路径下有没有这张图,如果有的话,直接调用ReturnLocalBitMap加载图片,如果没有的话,调用ReturnWebBitMap方法去调用网络图片并下载下来。
·后缀名都加了一个".image",目的是防止Android的图片浏览器去加载这些图片。
·ReturnWebBitMap中,先通过HTMLConnection获取图片的InputStream二进制流,然后通过op.inJustDecodeBounds = true; // 这个方法,获取一个只有高度等属性的Bitmap对象,接着根据图片原始大小获取需要大小的压缩比例op_new.inSampleSize = bili;。
·最后取到压缩过的Bitmap对象写入到内存卡或者直接显示均可。至此,图片的下载和保存已完成。
4. ChangeSizeBitMap解析
-
-
-
-
-
-
-
-
-
- publicstatic Bitmap ChangeSizeBitMap(Bitmap bt, int resize) {
- intsrc_width = bt.getWidth();
- intsrc_height = bt.getHeight();
- floatwidth = (float)bt.getWidth();
- floatheight = (float)bt.getHeight();
- floatbmpWidth = (float) resize / width;
- floatbmpHeight = (float) resize / height;
- if(width >= height) {
- if(width > resize) {
- bmpWidth= (float) resize / height;
- bmpHeight= bmpWidth;
- }
- }else{
- if(height > resize) {
- bmpHeight= (float) resize / height;
- bmpWidth= bmpHeight;
- }
- }
-
- if(bmpWidth > 1 || bmpHeight > 1) {
- returnbt;
- }
- Matrixmatrix = new Matrix();
- matrix.postScale(bmpWidth,bmpHeight);
- BitmapresizeBmp = Bitmap.createBitmap(bt, 0, 0, src_width, src_height, matrix, true);
- returnresizeBmp;
- }
这个方法里的东西就很简单了,不过计算的方式可以参考下,和下载图片时候的差不多,有更好的建议欢迎大家来指导一下。
============================================================================================================================
=============================================================================================================================
package com.android.tutor; |
002 | import android.graphics.Bitmap; |
003 | import android.graphics.Canvas; |
004 | import android.graphics.LinearGradient; |
005 | import android.graphics.Matrix; |
006 | import android.graphics.Paint; |
007 | import android.graphics.PixelFormat; |
008 | import android.graphics.PorterDuffXfermode; |
009 | import android.graphics.Rect; |
010 | import android.graphics.RectF; |
011 | import android.graphics.Bitmap.Config; |
012 | import android.graphics.PorterDuff.Mode; |
013 | import android.graphics.Shader.TileMode; |
014 | import android.graphics.drawable.Drawable; |
015 | public class ImageUtil { |
018 | public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h){ |
019 | int width = bitmap.getWidth(); |
020 | int height = bitmap.getHeight(); |
021 | Matrix matrix = new Matrix(); |
022 | float scaleWidht = (( float )w / width); |
023 | float scaleHeight = (( float )h / height); |
024 | matrix.postScale(scaleWidht, scaleHeight); |
025 | Bitmap newbmp = Bitmap.createBitmap(bitmap, 0 , 0 , width, height, matrix, true ); |
029 | public static Bitmap drawableToBitmap(Drawable drawable){ |
030 | int width = drawable.getIntrinsicWidth(); |
031 | int height = drawable.getIntrinsicHeight(); |
032 | Bitmap bitmap = Bitmap.createBitmap(width, height, |
033 | drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 |
034 | : Bitmap.Config.RGB_565); |
035 | Canvas canvas = new Canvas(bitmap); |
036 | drawable.setBounds( 0 , 0 ,width,height); |
037 | drawable.draw(canvas); |
043 | public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx){ |
045 | Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap |
046 | .getHeight(), Config.ARGB_8888); |
047 | Canvas canvas = new Canvas(output); |
049 | final int color = 0xff424242 ; |
050 | final Paint paint = new Paint(); |
051 | final Rect rect = new Rect( 0 , 0 , bitmap.getWidth(), bitmap.getHeight()); |
052 | final RectF rectF = new RectF(rect); |
054 | paint.setAntiAlias( true ); |
055 | canvas.drawARGB( 0 , 0 , 0 , 0 ); |
056 | paint.setColor(color); |
057 | canvas.drawRoundRect(rectF, roundPx, roundPx, paint); |
059 | paint.setXfermode( new PorterDuffXfermode(Mode.SRC_IN)); |
060 | canvas.drawBitmap(bitmap, rect, rect, paint); |
065 | public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap){ |
066 | final int reflectionGap = 4 ; |
067 | int width = bitmap.getWidth(); |
068 | int height = bitmap.getHeight(); |
070 | Matrix matrix = new Matrix(); |
071 | matrix.preScale( 1 , - 1 ); |
073 | Bitmap reflectionImage = Bitmap.createBitmap(bitmap, |
074 | 0 , height/ 2 , width, height/ 2 , matrix, false ); |
076 | Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height/ 2 ), Config.ARGB_8888); |
078 | Canvas canvas = new Canvas(bitmapWithReflection); |
079 | canvas.drawBitmap(bitmap, 0 , 0 , null ); |
080 | Paint deafalutPaint = new Paint(); |
081 | canvas.drawRect( 0 , height,width,height + reflectionGap, |
084 | canvas.drawBitmap(reflectionImage, 0 , height + reflectionGap, null ); |
086 | Paint paint = new Paint(); |
087 | LinearGradient shader = new LinearGradient( 0 , |
088 | bitmap.getHeight(), 0 , bitmapWithReflection.getHeight() |
089 | + reflectionGap, 0x70ffffff , 0x00ffffff , TileMode.CLAMP); |
090 | paint.setShader(shader); |
092 | paint.setXfermode( new PorterDuffXfermode(Mode.DST_IN)); |
094 | canvas.drawRect( 0 , height, width, bitmapWithReflection.getHeight() |
095 | + reflectionGap, paint); |
097 | return bitmapWithReflection; |