Android Development Learning Path-Image Color Picker development (1)

Source: Internet
Author: User

Series first, from a simple start, step by step to complete this small project.

Color acquisition is to analyze the color of each pixel in the picture, to analysis the whole picture of the master color, with the key color, we can be used in the picture of the card's background or title color, so the overall feeling more intense.

Interested can learn under the use of Google provided by palette, is also doing the same job, blog address: http://www.cnblogs.com/Fndroid/p/5201236.html

Look first:

The analysis principle is simple, is to get all the pixels of the picture color, then statistics, the number of statistics sorted, and then returned to the user.

But here are a few things to look at first:

① the process of getting color will not lead to UI line incurring;

② How to achieve sequencing (how to optimize the back study);

Because the analysis may not be done immediately when the image pixels are large, the parsing process should be done in the child thread, avoiding blocking the UI thread. Secondly, statistics and sorting can be implemented by the data structure provided by Java, regardless of performance factors, to realize the function first.

① in Android, images are generally represented by bitmap, while bitmap has a method called Getpixels:

 Public void int int int int int int int height)

The parameters are:

Pixiels: Storing an array that identifies the color

Offset: The starting subscript for an array

Stride: The amount of data per row, such as a 200*200 picture, when Stride is set to 200, pixels[200] is the first pixel color of the second row, when Stride is set to 400, pixels[200] is the additional information, Does not contain a color, and the first pixel of the second row should be in the color pixels[400]

X, Y: start x and Y

width, Height: You need to get the color's widths and heights, and X, y to form a rectangle

② after getting the color, the color is counted, because an array is obtained, so the logarithm of the group, if there is the same to add one, the number of occurrences of each color, the algorithm is simple as follows

New Hashmap<>();  for (int  pixel:pixels) {   = colors.get (pixel);    if NULL ) {       1);    Else {       + = 1;       Colors.put (pixel, num);}   }

③ sort, because need to return an ordered array, here convenient can use TreeMap direct row, note that TreeMap is the key sort, and the default is ascending

New Treemap<>();  for (Map.entry<integer, integer> entry:colors.entrySet ()) {    sortedcolors.put (Entry.getvalue (), Entry.getkey ());}

④ returns an ordered array, which is simply traversed and stored in the ArrayList.

New Arraylist<>();  for (Map.entry<integer, integer> entry:sortedColors.entrySet ()) {    Result.add (Entry.getvalue ()); }

⑤ If the function is called directly, it might block the UI, so use a sub-thread to do the work, and simply new A thread

⑥ in a child thread if the task finishes executing, send a message via handler to notify the UI update

The following gives the entire class:

 Public classColorcaptureutil {Private Static FinalString TAG = "Colorcaptureutil"; PrivateHandler Mhandler;  Public Static Final intSUCCESS = 1; /*** Construct A colorcaptureutil for analysing the color of the bitmap *@paramhandler when the analysing is done, it would is used to send back the result and call for update*/     PublicColorcaptureutil (Handler Handler) {Mhandler=handler; }    /*** Capture The bitmap's colors by counting every pixels, with the constructor ' s Handler to send back * message,  The ArrayList which contains the colors and sorted by the color quantity would is send * back with the message in the Message.obj *@parambitmap the bitmap for analysing*/     Public voidgetbitmapcolors (Bitmap Bitmap) {getbitmapcolors (Bitmap,0, 0, Bitmap.getwidth (), Bitmap.getheight ()); }    /*** Capture The bitmap's colors by counting every pixels, with the constructor ' s Handler to send back * message,  The ArrayList which contains the colors and sorted by the color quantity would is send * back with the message in the Message.obj *@parambitmap the bitmap for analysing *@paramFromX the start X in the bitmap, can is negative *@paramFromY the start Y in the bitmap, can is negative *@paramToX the end X in the bitmap, can not less than FromX *@paramToY the end Y in the bitmap, can not less than FromY*/     Public voidGetbitmapcolors (Bitmap Bitmap,intFromX,intFromY,intToX,intToY) {        NewThread (Newmyrunnable (Bitmap,fromx,fromy,tox,toy,mhandler)). Start (); }    Private classMyrunnableImplementsrunnable{PrivateBitmap Bitmap; Private intFromx,fromy,tox,toy; PrivateHandler Mhandler;  PublicMyrunnable (Bitmap Bitmap,intFromX,intFromY,intToX,intToY, Handler Handler) {             This. Bitmap =bitmap;  This. FromX =FromX;  This. FromY =FromY;  This. ToX =ToX;  This. ToY =ToY;  This. Mhandler =handler; } @Override Public voidrun () {int[] pixels =New int[Bitmap.getwidth () *bitmap.getheight ()]; HashMap<integer, integer> colors =NewHashmap<>(); TreeMap<integer, integer> sortedcolors =NewTreemap<>(); ArrayList<Integer> result =NewArraylist<>(); Bitmap.getpixels (Pixels,0, Bitmap.getwidth (), FromX, FromY, TOX-FROMX, ToY-FromY);  for(intpixel:pixels) {Integer num=colors.get (pixel); if(num = =NULL) {colors.put (pixel,1); } Else{num+ = 1;                Colors.put (pixel, num); }            }             for(Map.entry<integer, integer>Entry:colors.entrySet ())            {Sortedcolors.put (Entry.getvalue (), Entry.getkey ()); }             for(Map.entry<integer, integer>Entry:sortedColors.entrySet ())                {Result.add (Entry.getvalue ()); LOG.D (TAG,"Run:color:" +entry.getvalue () + ", Count:" +Entry.getkey ()); } Message msg=NewMessage (); Msg.obj=result; Msg.what=SUCCESS;        Mhandler.sendmessage (msg); }    }}

As you can see, you need a handler when you construct it, and when we finish processing the color data of the image, we use this handler to notify the UI thread. Then the statistical data into the message.obj, in the main thread directly out to get the color, the data is in ascending order, if you want the most color, you need to remove the size-1 value

Private New Handler () {        @Override        publicvoid  handlemessage (Message msg) {             if (Msg.what = = colorcaptureutil.success) {                ArrayList<Integer> colors = (arraylist<integer> ) msg.obj;                 -1));}}    ;

The first part of the content is relatively simple, because it is relatively simple, so there are still some problems to be solved

① resolution speed problem, consider whether you want to use other sorting algorithms? Do you need to process all pixel points? Can local sampling be performed?

② when the picture is the fourth (below), does the statistic appear to be the most pixel color reasonable?

③ is it reasonable to use the new thread directly? Is there a problem when there are a lot of pictures to deal with?

As soon as possible to update the next chapter, Welcome to communicate.

Android Development Learning Path-Image Color Picker development (1)

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.