android bitmap的 一些简单操作

全都是一些代码片段,需要可以直接贴过去用

			/** 获取 drawable 的图片   可以循环   1.图名    2.drawable 3.包名      **/
			
			int imgid = getResources().getIdentifier("ic_launcher", "drawable", "com.example.anywight");
			text.setBackgroundResource(imgid);
			
			
			/** 通过图片id获得Bitmap  **/
			Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
			
			
			/** 通过 assest 获取       获得Drawable    bitmap **/
			InputStream in = this.getAssets().open("ic_launcher");
			Drawable da = Drawable.createFromStream(in, null);
			Bitmap mm = BitmapFactory.decodeStream(in);
				
			/** 通过 sdcard  获得   bitmap **/
			Bitmap bit = BitmapFactory.decodeFile("/sdcard/android.jpg");
			
	

 

 xml bitmap (可以做出多种效果,类似用一张图 画出虚线等 边框效果,)

Android:antialias——开启或关闭抗锯齿

android:dither——开启或关闭图像抖动(如果位图与显示屏幕的像素配置不相同时会用到,比如一张ARGB 8888
位图和一个RGB565的显示屏)

android:filter——开启或关闭滤镜。当收缩或是拉伸位图时使用这个来使位图看上去更平滑。


android:gravity——当位图大小比它所在的容器小的时候,使用这个属性来决定位图在容器中的位置。可取的值
有:top、bottom、left、right、     center_vertical、fill_vertical(纵向缩放位图使之与容器等
高)、center_horizontal、fill_horizontal(横向缩放位图使之与容器等宽)、       center、
fill(纵向与橫向都缩放使之完全铺满容器,这也是默认值)、clip_vertical(呃。。。)、
clip_horizontal(呃。。。)。

android:tileMode——定义平铺模式。如果定义了,那么位图将会重复,并且Gravity属性将失效。可取的值有
disabled(默认值,不启用平铺)、     clamp(复制位图边缘的颜色来填充容器剩下的空白部分)、
repeat(复制整个位图来填充容器)、mirror(与repeat类似,但是是交替的镜像复       制,即相邻的
两张是镜像对称的)


 

<?xml version="1.0" encoding="utf-8"?>
    <bitmap
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:src="@[package:]drawable/drawable_resource"
  android:antialias=["true" | "false"]
  android:dither=["true" | "false"]
  android:filter=["true" | "false"]
  android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" |
           "fill_vertical" | "center_horizontal" | "fill_horizontal" |
           "center" | "fill" | "clip_vertical" | "clip_horizontal"]
  android:tileMode=["disabled" | "clamp" | "repeat" | "mirror"] />

 

 

 

 

 

 

 

	/** view转Bitmap **/
	public static Bitmap convertViewToBitmap(View view, int bitmapWidth, int bitmapHeight){
		
		Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
		view.draw(new Canvas(bitmap));
		return bitmap;
	}


	/** 将控件转换为bitmap **/
	public static Bitmap convertViewToBitMap(View view){
		// 打开图像缓存
		view.setDrawingCacheEnabled(true);
		// 必须调用measure和layout方法才能成功保存可视组件的截图到png图像文件
		// 测量View大小
		view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
		// 发送位置和尺寸到View及其所有的子View
		view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
		// 获得可视组件的截图
		Bitmap bitmap = view.getDrawingCache();
		return bitmap;
	}

	
	
	public static Bitmap getBitmapFromView(View view){
		Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(returnedBitmap);
		Drawable bgDrawable = view.getBackground();
		if (bgDrawable != null)
			bgDrawable.draw(canvas);
		else
			canvas.drawColor(Color.WHITE);
		view.draw(canvas);
		return returnedBitmap;
	}

	
	/**  获取屏幕截图的bitmap对象的代码如下  **/
	public Bitmap getScreenPic(View view){
		
		View rootView = view.getRootView();
		rootView.setDrawingCacheEnabled(true);
		rootView.buildDrawingCache();
		// 不明白为什么这里返回一个空,有帖子说不能在oncreat方法中调用
		// 测量View大小
		rootView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
		// 发送位置和尺寸到View及其所有的子View
		rootView.layout(0, 0, rootView.getMeasuredWidth(), rootView.getMeasuredHeight());
		// 解决措施,调用上面的measure和layout方法之后,返回值就不再为空
		// 如果想要创建的是固定长度和宽度的呢?
		Bitmap bitmap = rootView.getDrawingCache();
		rootView.destroyDrawingCache();
		return bitmap;
	}

	
	/** 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;

	}
	
	
	/** bitmap → drawable **/
	public static Drawable bitmapToDrawable(Context context,String filename){
		
		 Bitmap image = null;  
	     BitmapDrawable ddd = null;  
	        try {  
	            AssetManager am = context.getAssets();  
	            InputStream is = am.open(filename);  
	            image = BitmapFactory.decodeStream(is);  
	            ddd = new BitmapDrawable(context.getResources(), image);  
	            is.close();  
	        } catch (Exception e) {  
	        }  
	     return ddd;  

	}
	
	
	/** byte[] → Bitmap **/
	public static Bitmap byteToDrawable(Context context,byte[] bb){
	     Bitmap pp  = BitmapFactory.decodeByteArray(bb, 0, bb.length);
	     return pp;
	}
	
	
	/**  Bitmap → byte[]**/
	public static byte[] bitmapToByte(Bitmap bitmap){
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();  
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);  
	    byte[] yy = baos.toByteArray();
	    return yy;
	}
	

	/**  将text  转换成  bitmap  **/
	public static Bitmap createTxtImage(String txt, int txtSize) {
        Bitmap mbmpTest = Bitmap.createBitmap(txt.length() * txtSize + 4,
                txtSize + 4, Config.ARGB_8888);
        Canvas canvasTemp = new Canvas(mbmpTest);
        Paint p = new Paint();
        p.setAntiAlias(true);
        p.setColor(Color.WHITE);
        p.setTextSize(txtSize);
        canvasTemp.drawText(txt, 2, txtSize - 2, p);
        return mbmpTest;

    }
	
	/**  显示将bitmap进行缩放       **/
	public Bitmap  bitmapScanel(Context context){
		//通过openRawResource获取一个inputStream对象  
	    InputStream inputStream = context.getResources().openRawResource(R.id.backageground);  
	    //通过一个InputStream创建一个BitmapDrawable对象  
	    BitmapDrawable drawable = new BitmapDrawable(inputStream);  
	    //通过BitmapDrawable对象获得Bitmap对象  
	    Bitmap bitmap = drawable.getBitmap();  
	    //利用Bitmap对象创建缩略图  
	    bitmap = ThumbnailUtils.extractThumbnail(bitmap, 40, 40);  
	    return bitmap;
   	
	 }
	
	  /**  放大缩小图片    **/  
    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;  
    }  
	
	
    
    /** 获得圆角图片的方法  **/  
    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;  
    }  
    
    

	/** 对 bitmap 进行裁剪     **/
	public Bitmap  bitmapClip(Context context , int id , int x , int y){
		 Bitmap map = BitmapFactory.decodeResource(context.getResources(), id);
		 map = Bitmap.createBitmap(map, x, y, 120, 120);
	     return map;
	}
	
	

	/**
	 * 图片的倒影效果
	 */
	public static Bitmap createReflectedImage(Bitmap originalImage) {
        final int reflectionGap = 4;

        int width = originalImage.getWidth();
        int height = originalImage.getHeight();

        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);

        // Create a Bitmap with the flip matrix applied to it.
        // We only want the bottom half of the image
        Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
                height / 2, width, height / 2, matrix, false);

        // Create a new bitmap with same width but taller to fit reflection
        Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
                (height + height / 2), Config.ARGB_8888);

        // Create a new Canvas with the bitmap that's big enough for
        // the image plus gap plus reflection
        Canvas canvas = new Canvas(bitmapWithReflection);
        // Draw in the original image
        canvas.drawBitmap(originalImage, 0, 0, null);
        // Draw in the gap
        Paint defaultPaint = new Paint();
        canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);
        // Draw in the reflection
        canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

        // Create a shader that is a linear gradient that covers the reflection
        Paint paint = new Paint();
        LinearGradient shader = new LinearGradient(0,
                originalImage.getHeight(), 0, bitmapWithReflection.getHeight()
                        + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
        // Set the paint to use this shader (linear gradient)
        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;
     }
	
	

 

获取屏幕的截图,并且保存到sdcard

 

 

	/**  获取屏幕截图       **/
    public  static Bitmap takeScreenShot(Activity activity) {  
    	
        View view = activity.getWindow().getDecorView();  
        view.setDrawingCacheEnabled(true);  
        /** 创建图像缓存 **/
        view.buildDrawingCache();  
        /** 获取图像缓存 **/
        Bitmap b1 = view.getDrawingCache();  
  
        // 获取状态栏的高度
        Rect frame = new Rect();  
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
        int statusBarHeight = frame.top;  
      
 
        // 获取屏幕宽高 
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();  
        int height = activity.getWindowManager().getDefaultDisplay().getHeight();  
                 
  
       // 去掉状态栏 
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height- statusBarHeight);   
          
       view.destroyDrawingCache();  
       return b;  
    }  


    // 保存到sdcard  
    private static void savePic(Bitmap b, String strFileName) {  
    	
        FileOutputStream fin = null;  
        try {  
        	fin = new FileOutputStream(strFileName);   
            if (null != fin) {  
                b.compress(Bitmap.CompressFormat.PNG, 90, fin);  
                fin.flush();  
                fin.close();  
              
            }  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {
           e.printStackTrace();  
        }  
    }  

 

 

获取视频的预览图片

 }  
    
    
    /**  对视频数据进行截图     **/
    private Bitmap createVideoThumbnail(String filePath) { //传进的参数为本地视频文件的path 
       
    	Bitmap bitmap = null; 
    	
    	//android 3.0以后有的
        android.media.MediaMetadataRetriever retriever = new android.media.MediaMetadataRetriever();         

    	// android 2.2以后有的   2.2之前也又方法 其实也是用 android.media.MediaMetadataRetriever 可以百度一下
//    	Bitmap  b = ThumbnailUtils.createVideoThumbnail(path,Video.Thumbnails.MICRO_KIND); 这样就获得了
        try{
            retriever.setDataSource(filePath);    
            String timeString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);  
            long time = Long.parseLong(timeString) * 1000;  
            Log.i("TAG","time = " + time);  
            bitmap = retriever.getFrameAtTime(time*31 / 160); //按视频长度比例选择帧  
      
        } catch (IllegalArgumentException ex) {  
        	
        } catch (RuntimeException ex) {  
            // Assume this is a corrupt video file.  
        } finally {  
            try {  
                retriever.release();  
            } catch (RuntimeException ex) {  
                // Ignore failures while cleaning up.  
           }  
        }  
        return bitmap;  
   }  

 

截取无状态栏的当前屏幕图片,使图片高斯模糊的方法请参考blurBitmap方法

ByteArrayOutputStream baos=new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

byte [] bitmapByte =baos.toByteArray()

 

 

 

publicclassScreenShotUtil{
// 获取指定Activity的截屏,保存到png文件
    String filenameTemp = "/mnt/sdcard/temp";
/**
     * takeScreenShot:
     * TODO 截屏    去掉标题栏
     * @param activity
     */
publicstatic Bitmap takeScreenShot(Activity activity){
// View是你需要截图的View
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();
// 获取状态栏高度
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
        LogHelper.i("TAG", "" + statusBarHeight);
// 获取屏幕长和高
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay().getHeight();
// 去掉标题栏
// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
return b;
    }
/**
     * TODO  用于高效的图片处理,包括模糊、混合、矩阵卷积计算等
     * @param bitmap
     * @param context
     */
@SuppressLint("NewApi")
publicstatic Bitmap blurBitmap(Bitmap bitmap, Context context){
// Let's create an empty bitmap with the same size of the bitmap we want
// to blur
        Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
                Config.ARGB_8888);
// Instantiate a new Renderscript
        RenderScript rs = RenderScript.create(context);//RenderScript是Android在API 11之后加入的
// Create an Intrinsic Blur Script using the Renderscript
        ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
// Create the Allocations (in/out) with the Renderscript and the in/out
// bitmaps
        Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
        Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);
// Set the radius of the blur
        blurScript.setRadius(25.f);
// Perform the Renderscript
        blurScript.setInput(allIn);
        blurScript.forEach(allOut);
// Copy the final bitmap created by the out Allocation to the outBitmap
        allOut.copyTo(outBitmap);
// recycle the original bitmap
        bitmap.recycle();
// After finishing everything, we destroy the Renderscript.
        rs.destroy();
return outBitmap;
    }
}
/**
     * blurImageAmeliorate:模糊效果
     * http://blog.csdn.net/sjf0115/article/details/7266998
     * @param bmp
     * @return
     */
publicstatic Bitmap blurImageAmeliorate(Bitmap bmp)
    {  
long start = System.currentTimeMillis();  
// 高斯矩阵  
int[] gauss = newint[] { 1, 2, 1, 2, 4, 2, 1, 2, 1 };  
int width = bmp.getWidth();  
int height = bmp.getHeight();  
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
int pixR = 0;  
int pixG = 0;  
int pixB = 0;  
int pixColor = 0;  
int newR = 0;  
int newG = 0;  
int newB = 0;  
int delta = 75; // 值越小图片会越亮,越大则越暗  
int idx = 0;  
int[] pixels = newint[width * height];  
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);  
for (int i = 1, length = height - 1; i < length; i++)  
        {  
for (int k = 1, len = width - 1; k < len; k++)  
            {  
                idx = 0;  
for (int m = -1; m <= 1; m++)  
                {  
for (int n = -1; n <= 1; n++)  
                    {  
                        pixColor = pixels[(i + m) * width + k + n];  
                        pixR = Color.red(pixColor);  
                        pixG = Color.green(pixColor);  
                        pixB = Color.blue(pixColor);  
                        newR = newR + (int) (pixR * gauss[idx]);  
                        newG = newG + (int) (pixG * gauss[idx]);  
                        newB = newB + (int) (pixB * gauss[idx]);  
                        idx++;  
                    }  
                }  
                newR /= delta;  
                newG /= delta;  
                newB /= delta;  
                newR = Math.min(255, Math.max(0, newR));  
                newG = Math.min(255, Math.max(0, newG));  
                newB = Math.min(255, Math.max(0, newB));  
                pixels[i * width + k] = Color.argb(255, newR, newG, newB);  
                newR = 0;  
                newG = 0;  
                newB = 0;  
            }  
        }  
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);  
long end = System.currentTimeMillis();  
return bitmap;  
    }  

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

空白的泡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值