[Android] adds image frames, rounded corners, and image synthesis knowledge to images.

Source: Internet
Author: User
Tags border image

[Android] adds image frames, rounded corners, and image synthesis knowledge to images.

The previous article describes how to use the Android touch screen setOnTouchListener to achieve breakthrough scaling, movement, painting, and adding watermarks, continue to my "" project to complete the function introduction of adding a photo frame, a circular rounded corner to the image and image synthesis to the image. I hope this article will help you.

1. Open the image and display the image in the assets File

First, layout activity_main.xml in XML by using RelativeLayout relative layout (attached to the XML Code). Then,Add the following code to the public class MainActivity extends Activity function in Mainctivity. java:

 

// Control private Button openImageBn; // open the image private Button showImageBn; // display the assets resource image private Button showImageBn1; // Add private Button showImageBn2 to Mode 1; // Mode 2 plus private Button roundImageBn; // rounded corner image private ImageView imageShow; // display image // custom variable private Bitmap bmp; // original image private final int IMAGE_OPEN = 0; // open the image private Canvas canvas; // Canvas private Paint; // painter @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // open the image openImageBn = (Button) findViewById (R. id. button1); imageShow = (ImageView) findViewById (R. id. imageView1); openImageBn. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {Intent intent = new Intent (Intent. ACTION_PICK, android. provider. mediaStore. images. media. EXTERNAL_CONTENT_URI); startActivityForResult (intent, IMAGE_OPEN) ;}}); if (savedInstanceState = null) {getFragmentManager (). beginTransaction (). add (R. id. container, new PlaceholderFragment ()). commit () ;}// open the image protected void onActivityResult (int requestCode, int resultCode, Intent data) {super. onActivityResult (requestCode, resultCode, data); if (resultCode = RESULT_ OK & requestCode = IMAGE_OPEN) {Uri imageFileUri = data. getData (); DisplayMetrics dm = new DisplayMetrics (); getWindowManager (). getdefadisplay display (). getMetrics (dm); int width = dm. widthPixels; // The horizontal resolution of the phone screen. int height = dm. heightPixels; // mobile phone screen vertical resolution try {// loading image size not loaded into the image itself true BitmapFactory. options BMP factoryoptions = new BitmapFactory. options (); BMP factoryoptions. inJustDecodeBounds = true; bmp = BitmapFactory. decodeStream (getContentResolver (). openInputStream (imageFileUri), null, BMP factoryoptions); int heightRatio = (int) Math. ceil (BMP factoryoptions. outHeight/(float) height); int widthRatio = (int) Math. ceil (BMP factoryoptions. outWidth/(float) width); // inSampleSize indicates the proportion of the image to the original image. 1 indicates the original image if (heightRatio> 1 & widthRatio> 1) {if (heightRatio> widthRatio) {BMP factoryoptions. inSampleSize = heightRatio;} else {BMP factoryoptions. inSampleSize = widthRatio ;}// the image is decoded to false. inJustDecodeBounds = false; bmp = BitmapFactory. decodeStream (getContentResolver (). openInputStream (imageFileUri), null, BMP factoryoptions); imageShow. setImageBitmap (bmp);} catch (FileNotFoundException e) {e. printStackTrace () ;}// end if}

You can click the "open" button above to open the image. When adding a border for the image, it is actually achieved through the synthesis of two or more images.
In jacpy. in may's Android image processing summary, we recommend that you do not place images in the drawable directory because the screen resolution affects the image size. it is best to put it in the assets Directory, which represents the native resources that the application cannot directly access (usually loading PNG transparent images to achieve border synthesis). It can only be read in the stream mode and smaller than 1 M.
To read images in the assets folder, manually add the PNG image to the assets Directory and add the following code to the omCreate function:

 

// Display the image showImageBn = (Button) findViewById (R. id. button2); showImageBn. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {Bitmap bitmap = getImageFromAssets ("image01.png"); imageShow. setImageBitmap (bitmap );}});
Then, use the custom function getImageFromAssets to obtain the image "image01.png ":

 

// Obtain resources in assets and convert them to Bitmapprivate Bitmap getImageFromAssets (String fileName) {// use the assets Directory in Android to store resources, it indicates the native resource Bitmap imageAssets = null that the application cannot directly access; AssetManager am = getResources (). getAssets (); try {InputStream is = am. open (fileName); imageAssets = BitmapFactory. decodeStream (is); is. close ();} catch (IOException e) {e. printStackTrace ();} return imageAssets ;}
Shows the display effect:

The XML Code is as follows:

 

     
  
 2. Add photo frames and Image Synthesis
Then, we start to complete image synthesis. Here we use two methods to complete the process. Continue to add code to the onCreate function:
// Mode 1 merge Image showImageBn1 = (Button) findViewById (R. id. button3); listener (new OnClickListener () {@ Overridepublic void onClick (View v) {Bitmap bitmap = getImageFromAssets ("image01.png"); addFrameToImage (bitmap );}});
The User-Defined Function addFrameToImage is used to load image synthesis. first, create an empty image object, which is the same size and configuration as the opened image. Then, create a Canvas object and a Paint object to draw the first bitmap object on the Canvas, it becomes the goal of merging operations.
Now, set the transition mode on the Paint object, and instantiate a new porterduxfermode object by passing in a constant that defines the operation mode. then draw the second bitmap object on the Canvas object, and set the ImageView as the new bitmap object. the Code is as follows:
// Image synthesis 1 private void addFrameToImage (Bitmap bm) // bmp source image (foreground) bm resource image (background) {Bitmap drawBitmap = Bitmap. createBitmap (bmp. getWidth (), bmp. getHeight (), bmp. getConfig (); canvas = new Canvas (drawBitmap); paint = new Paint (); canvas. drawBitmap (bmp, 0, 0, paint); paint. setXfermode (new porterduduxfermode (android. graphics. porterDuff. mode. LIGHTEN); // scale the border to int w = bm. getWidth (); int h = bm. getHeight (); // if the image size exceeds the border size, the system automatically matches float scaleX = bmp. getWidth () * 1F/w; float scaleY = bmp. getHeight () * 1F/h; Matrix matrix = new Matrix (); matrix. postScale (scaleX, scaleY); // scales the image Bitmap copyBitmap = Bitmap. createBitmap (bm, 0, 0, w, h, matrix, true); canvas. drawBitmap (copyBitmap, 0, 0, paint); imageShow. setImageBitmap (drawBitmap );}
The second method is to refer to Android multimedia development advanced programming, but the synthesis of the image fourteen is not very good:
// Mode 2 merge Image showImageBn2 = (Button) findViewById (R. id. button4); showImageBn2.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {Bitmap bitmap = getImageFromAssets ("image07.png"); // The second synthesis method is imageShow. setImageBitmap (addFrameToImageTwo (bitmap ));}});
Then implement the following using a custom function:
// Image synthesis private Bitmap addFrameToImageTwo (Bitmap frameBitmap) // bmp source image frameBitmap resource image (Border) {// create a new Bitmap int width = bmp in the bmp source image. getWidth (); int height = bmp. getHeight (); Bitmap drawBitmap = Bitmap. createBitmap (width, height, Config. RGB_565); // scale the border to int w = frameBitmap. getWidth (); int h = frameBitmap. getHeight (); float scaleX = width * 1F/w; // if the image size exceeds the border size, the system automatically matches float scaleY = height * 1F/h; Matrix matrix = New Matrix (); matrix. postScale (scaleX, scaleY); // scales the image Bitmap copyBitmap = Bitmap. createBitmap (frameBitmap, 0, 0, w, h, matrix, true); int pixColor = 0; int layColor = 0; int newColor = 0; int pixR = 0; int pixG = 0; int pixB = 0; int pixA = 0; int newR = 0; int newG = 0; int newB = 0; int newA = 0; int layR = 0; int layG = 0; int layB = 0; int layA = 0; float alpha = 0.8F; float alphaR = 0F; f Loat alphaG = 0F; float alphaB = 0F; for (int I = 0; I <width; I ++) {for (int k = 0; k 
Its running effect is as follows. The first two figures show method 1, but its synthesis effect is not very good. The third figure shows the second method, however, the response time is a little longer.

In the first method, the poterduxfermode class was used as the transition mode, which was named after Thomas Porter and Tom Duff. In 1984, they published "Compositing digital images (synthetic digital images)" In acm siggraph computer graphics) this article introduces different rules for overlapping images. these rules define which parts of the image will appear in the result output.
The PorterDuff. Mode class in Android lists the rules set by Porter and Duff and more people.
Android. graphics. PorterDuff. Mode. SRC: This rule means that only the source image is drawn. Currently, it is the Paint object that applies this rule.
Android. graphics. PorterDuff. Mode. DST: This rule means that only the target image is displayed, and the initial image on the existing canvas is displayed.
As shown in, the Mode value is defined as follows:

Here, there are four rules that define how to synthesize the two images when one image is placed on the other, which are frequently used values:
Android. graphics. PorterDuff. Mode. LIGHTEN: Obtain and display the brightest pixels in the two images at each position.
Android. graphics. PorterDuff. Mode. DARKEN: obtains and displays the lowest pixels in the two images at each position.
An Droid. graphics. porterDuff. mode. MULTIPLY: MULTIPLY two pixels at each position by 255. Use this value to create a new Pixel for display. result color = Top color * bottom color/255.
AnDroid. graphics. porterDuff. mode. SCREEN: Invert each color and perform the same operation. result color = 255-(255-top color) * (255-bottom color)/255)

 

3. Show the circular and rounded rectangular images The following code is added to the onCreate function:
// RoundImageBn = (Button) findViewById (R. id. button5); roundImageBn. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {imageShow. setImageBitmap (getRoundedCornerBitmap (bmp ));}});
Then use the custom function getRoundedCornerBitmap to implement the circle:
// Generate the rounded corner image private Bitmap getRoundedCornerBitmap (Bitmap bitmap) {Bitmap roundBitmap = Bitmap. createBitmap (bitmap. getWidth (), bitmap. getHeight (), Config. ARGB_8888); Canvas canvas = new Canvas (roundBitmap); int color = 0xff0000242; Paint paint = new Paint (); // set the circular radius int radius; if (bitmap. getWidth ()> bitmap. getHeight () {radius = bitmap. getHeight ()/2;} else {radius = bitmap. getWidth ()/2;} // draw a circular paint. setAntiAlias (true); canvas. drawARGB (0, 0, 0, 0); paint. setColor (color); canvas. drawCircle (bitmap. getWidth ()/2, bitmap. getHeight ()/2, radius, paint); paint. setXfermode (new porterduduxfermode (Mode. SRC_IN); canvas. drawBitmap (bitmap, 0, 0, paint); return roundBitmap ;}
Similarly, if you replace the content in the function, the circular rectangle is displayed:
Private Bitmap getRoundedCornerBitmap (Bitmap bitmap) {// draw a rounded rectangle Bitmap roundBitmap = Bitmap. createBitmap (bitmap. getWidth (), bitmap. getHeight (), Config. ARGB_8888); Canvas canvas = new Canvas (roundBitmap); int color = 0xff0000242; Paint paint = new Paint (); Rect rect = new Rect (0, 0, bitmap. getWidth (), bitmap. getHeight (); RectF rectF = new RectF (rect); float roundPx = 80; // set the corner to 80 // paint. setAntiAlias (true); canvas. drawARGB (0, 0, 0, 0); paint. setColor (color); canvas. drawRoundRect (rectF, roundPx, roundPx, paint); paint. setXfermode (new porterduduxfermode (Mode. SRC_IN); canvas. drawBitmap (bitmap, rect, rect, paint );}
Shows the running result:
Summary:
This article mainly describes how to add a photo frame to an image, display the image with rounded corners, and describe the image synthesis. It mainly uses the source code and detailed processes. Why should I write this article? In image processing, I think that adding borders, changing borders, and merging images belong to the same type of changes and rendering.The image processing software has not yet been integrated. We recommend that you read the two books in the following documents.
Finally, I hope the article will help you. If there are any deficiencies or errors, please forgive me! In any case, I think this article is well written. I 'd like to give myself a compliment! Fuel \ (^ o ^ )/~
:
Shows the basic source code format:

(By: EastmountHttp://blog.csdn.net/eastmount)

References and recommended blog posts: 1. I would like to thank the authors of Android multimedia development advanced programming and Android image processing:Jacpy. may, A lot of information on the Internet is them.
2. android image processing Series 6-Add a border (bottom) to the image-overlay the image
Author-SJF0115: He reproduced some articles in the book, which is also very good.
3. Android image synthesis: Implementation of opacity gradient effects of irregular Photo Frames
The author-HappyDelano, a very good article, tells about the effect of four figures to achieve the heart-to-heart display.
4. johnlxj, author of Android image synthesis, describes the implementation process of image synthesis.
5. Android perfectly achieves image rounded corners and circles (for Implementation Analysis)
Author-Hongyang _ many of the author's android articles are very good
6. android image reflection recommended by setXfermode author-lipeng88213
7. For Android ImageView, click "select" and add the border author-black rice porridge. This method is used in image switching.
8. android enables online instant chat with ease [images, voices, expressions, and texts]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.