All are some code snippets, which can be directly pasted and used if needed.
/** Get the picture of the drawable can cycle 1. Picture name 2. drawable 3. Package name **/ int imgid = getResources().getIdentifier("ic_launcher", "drawable", "com.example.anywight"); text.setBackgroundResource(imgid); /** Get Bitmap by image id **/ Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); /** Get Drawable bitmap through assert **/ InputStream in = this.getAssets().open("ic_launcher"); Drawable da = Drawable.createFromStream(in, null); Bitmap mm = BitmapFactory.decodeStream(in); /** Get bitmap through sdcard **/ Bitmap bit = BitmapFactory.decodeFile("/sdcard/android.jpg");
xml bitmap (can make a variety of effects, similar to using a picture to draw border effects such as dotted lines,)
Android:antialias - turn on or off anti-aliasing
android:dither - turn on or off image dithering (used if the bitmap is not the same as the pixel configuration of the display screen, such as an ARGB 8888
bitmap and an RGB565 display )
android:filter - turn the filter on or off. Use this to make the bitmap look smoother when shrinking or stretching it.
android:gravity - When the size of the bitmap is smaller than the container it is in, use this attribute to determine the position of the bitmap in the container. The available values
are: top, bottom, left, right, center_vertical, fill_vertical (scale the bitmap vertically to make it the same
height as the container), center_horizontal, fill_horizontal (scale the bitmap horizontally to make it the same width as the container), center,
fill (vertical scale). Scale both horizontally and horizontally to completely fill the container, which is also the default), clip_vertical (uh...),
clip_horizontal (uh...).
android:tileMode - defines the tile mode. If defined, the bitmap will be duplicated and the Gravity property will have no effect. Available values are
disabled (the default value, do not enable tiling), clamp (copy the color of the edge of the bitmap to fill the remaining blank part of the container),
repeat (copy the entire bitmap to fill the container), mirror (similar to repeat, But it is an alternate mirror copy, that is, the adjacent
two are mirror-symmetrical)
<?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 to 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; } /** Convert control to bitmap **/ public static Bitmap convertViewToBitMap(View view){ // open image cache view.setDrawingCacheEnabled(true); // The measure and layout methods must be called to successfully save a screenshot of the displayable to a png image file // measure the view size view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); // Send the position and size to the View and all its children view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); // Get a screenshot of the displayable 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; } /** The code to get the bitmap object of the screenshot is as follows**/ public Bitmap getScreenPic(View view){ View rootView = view.getRootView(); rootView.setDrawingCacheEnabled(true); rootView.buildDrawingCache(); // I don't understand why an empty is returned here, some posts say that it cannot be called in the oncreat method // measure the view size rootView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); // Send the position and size to the View and all its children rootView.layout(0, 0, rootView.getMeasuredWidth(), rootView.getMeasuredHeight()); // Solution, after calling the above measure and layout methods, the return value is no longer empty // What if you want to create a fixed length and width? 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; } /** Convert text to 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; } /** Display scaling bitmap **/ public Bitmap bitmapScanel(Context context){ //Get an inputStream object through openRawResource InputStream inputStream = context.getResources().openRawResource(R.id.backageground); //Create a BitmapDrawable object through an InputStream BitmapDrawable drawable = new BitmapDrawable(inputStream); //Get the Bitmap object through the BitmapDrawable object Bitmap bitmap = drawable.getBitmap(); / / Use the Bitmap object to create a thumbnail bitmap = ThumbnailUtils.extractThumbnail(bitmap, 40, 40); return bitmap; } /** Zoom in and zoom out the image**/ 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; } /** How to get rounded image **/ 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; } /** Crop the 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; } /** * Reflection effect of pictures */ 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; }
Take a screenshot of the screen and save it to sdcard
/** Get screenshot**/ public static Bitmap takeScreenShot(Activity activity) { View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); /** Create image cache**/ view.buildDrawingCache(); /** Get image cache**/ Bitmap b1 = view.getDrawingCache(); // Get the height of the status bar Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; // Get screen width and height int width = activity.getWindowManager().getDefaultDisplay().getWidth(); int height = activity.getWindowManager().getDefaultDisplay().getHeight(); // remove the status bar Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height- statusBarHeight); view.destroyDrawingCache(); return b; } // save to 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 (); } }
} /** Take a screenshot of the video data**/ private Bitmap createVideoThumbnail(String filePath) { //The passed parameter is the path of the local video file Bitmap bitmap = null; //some after android 3.0 android.media.MediaMetadataRetriever retriever = new android.media.MediaMetadataRetriever(); // After android 2.2, some methods before 2.2 are also used android.media.MediaMetadataRetriever to Baidu // Bitmap b = ThumbnailUtils.createVideoThumbnail(path,Video.Thumbnails.MICRO_KIND); This gets 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); //Select frames according to the video length ratio } 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; }