Method and system for extracting theme color of picture based on javascript
By using JavaScript on the web front-end, creating Image objects and canvas canvas, extracting pixel data of the image and counting color information, the problems of high cost and complex operation of image theme color extraction in the existing technology are solved, and fast, flexible and efficient image theme color extraction is achieved.
Patent Information
- Application Number
- CN202411736151.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-11-29
- Publication Date
- 2025-02-25
AI Technical Summary
In the prior art, machine learning color analysis methods are technically costly and complex in operation, while backend management system configuration methods are complex and not flexible enough, making it difficult to effectively extract the theme colors of pictures.
Using a JavaScript-based method, by creating an Image object and a canvas canvas, obtaining pixel data of the image, counting the number of occurrences of each color information, and determining the color information with the most occurrences as the theme color of the image.
It realizes the direct extraction of image theme colors on the client side, avoids dependence on expensive tools or complex hardware, reduces cost and operational complexity, improves extraction speed and efficiency, and is suitable for various network environments.
Smart Images

Figure CN119512697A_ABST
Abstract
Description
Technical Field
[0001] The invention belongs to the technical field of front-end development, and relates to a method and system for extracting picture theme colors based on javascript. Background Art
[0002] In current Internet applications, images are an important carrier of information and are widely used in various websites and applications. In order to improve user experience and visual effects, developers often need to dynamically adjust the background color according to the image content. Especially in a weak network environment, when the image loads slowly, a suitable background color fill can significantly improve the visual coherence of the page and the user's waiting comfort. In addition, for websites that display different images, dynamically changing background colors can also add novelty to the design and enhance the user's visual experience.
[0003] In the prior art, the following two methods are mainly used to extract the theme color of an image:
[0004] Machine learning color analysis uses machine learning algorithms to perform in-depth analysis on images, thereby accurately extracting the theme color of the image. Although this method has a high performance in terms of accuracy, its technical cost is relatively high and requires professional algorithm development and a large amount of computing resources. For general Web application developers, it is difficult to implement and maintain such a system.
[0005] Another method is to manually configure the theme color for each picture through the backend management system. Although the background color can be customized to a certain extent, the operation is complicated, costly, and not flexible enough. Once the picture library is updated or changed, it needs to be reconfigured, which greatly increases the maintenance cost.
[0006] In view of the above shortcomings of the prior art, the present invention proposes a method for extracting the theme color of an image based on JavaScript. The method makes full use of the characteristics of the Web front-end development language and directly implements the extraction of the theme color of the image and the filling of the background color on the client through JavaScript. Summary of the invention
[0007] The purpose of the present invention is to solve the problem that the existing technology of color analysis of pictures by machine learning is of high technical cost and complicated operation, and to provide a method and system for extracting the theme color of pictures based on javascript.
[0008] In order to achieve the above object, the present invention adopts the following technical solutions:
[0009] A method for extracting the theme color of an image based on javascript, comprising the following steps:
[0010] Create an Image object and assign the image resource to be processed to the src attribute of the Image object to load the image resource;
[0011] In the onload event of the Image object, get the loaded image object;
[0012] Create a canvas and get the 2D rendering context object context of the canvas;
[0013] Use the context's drawImage method to draw the obtained image object onto the canvas;
[0014] Get the pixel data of the image drawn on the canvas through the getImageData method of canvas. The pixel data is an array composed of RGBA values.
[0015] Process the acquired pixel data and group every four consecutive RGBA values into a group to represent the color information of the pixel;
[0016] Count the processed color information and record the number of times each color information appears;
[0017] Get the color information that appears most times, which is the theme color of the image.
[0018] The creation of the Image object specifically includes the following steps:
[0019] Use JavaScript's new keyword to create an Image object, which is used to represent and display images on a Web page.
[0020] Assign the URL of the image resource to be processed to the src attribute of the created Image object to trigger the browser to load the image resource;
[0021] Use the onload event of the Image object to set the event processing function, which is called after the image resource is loaded;
[0022] In the set event handling function, write the code logic after the image is loaded, and use the drawImage method of canvas to draw the loaded image onto the canvas.
[0023] The process of creating a canvas and obtaining a 2D rendering context object context of the canvas specifically includes the following steps:
[0024] In an HTML document, by <canvas>The tag directly defines a canvas element with a unique id identifier, specified width and height, and then adds the canvas element to the document's DOM structure;
[0025] If the canvas element has been defined in HTML, use document.getElementById method and pass in the id identifier of the canvas element to get the element; if the canvas element is created dynamically, directly use the reference obtained when it was created;
[0026] Use the getContext('2d') method of the obtained canvas element to obtain a 2D rendering context object, which provides an API for drawing 2D graphics on the canvas.
[0027] If the 2D rendering context object is successfully obtained, the API provided by the object is used to perform graphics drawing operations on the canvas.
[0028] The pixel data of the image drawn on the canvas is obtained through the getImageData method of canvas. The specific steps are:
[0029] Determine the pixel data area to be obtained from the canvas, where the area is defined by a rectangle, including the horizontal coordinate x of the upper left corner of the rectangle, the vertical coordinate of the upper left corner, the width of the rectangle, and the height of the rectangle; the rectangular area covers the entire canvas or a specific part of the canvas;
[0030] Call the getImageData method of the CanvasRenderingContext2D object and pass in four parameters of the determined rectangular area to obtain an ImageData object; the ImageData object returned by the getImageData method contains a data attribute array, and the elements in the array represent the RGBA value of each pixel in the specified area;
[0031] Get the data property of the obtained ImageData object to access the pixel data array; each pixel in the array consists of four consecutive elements, representing the values of red R, green G, blue B, and transparency alpha, and the value range is 0 to 255.
[0032] The pixel data is processed and every four consecutive RGBA values are grouped into one group, specifically:
[0033] Data preparation step, get the pixel data array containing the color information of all pixels in the image from the ImageData object, where the color of each pixel is represented by four consecutive values, corresponding to the intensity of red R, green G, blue B and transparency alpha;
[0034] Initialize the index step and set the index variable for traversing the pixel data array. When initialized, the index points to the first element of the array.
[0035] Group processing steps:
[0036] Index range check substep, before each iteration, ensure that the current value of the index variable plus 3 does not exceed the length of the pixel data array to avoid array out of bounds;
[0037] The RGBA value extraction sub-step reads the values of the current index and the three positions after it from the array. These four values represent the R, G, B, and A values of a pixel point respectively.
[0038] In the group storage sub-step, the four extracted values are regarded as a group representing the color information of a pixel, and the group of values is stored in a new data structure as needed;
[0039] Index update sub-step: After each iteration, the index variable is increased by 4 to process the color information of the next pixel;
[0040] Iterate and repeat the sub-step, repeatedly execute the index range check sub-step, RGBA value extraction sub-step, group storage sub-step and index update sub-step until the index variable exceeds the length of the pixel data array, that is, the color information of all pixels is processed.
[0041] The statistics of the processed color information are specifically as follows:
[0042] Initialize the statistics structure and create a data structure to store each color and its number of occurrences;
[0043] Iterate over the pixel data, iterate over the pixel data array provided by the data property of the ImageData object. Each pixel in the array consists of four consecutive elements, and the elements are processed one by one through a loop;
[0044] Calculate the color hash value. If you choose to use the hash value as the key, define a function to calculate the hash value of a given RGBA value.
[0045] Update the statistics structure. For each pixel in the array, find the corresponding entry in the statistics structure according to its RGBA value or the calculated hash value. If the entry exists, increase its occurrence count by 1. If the entry does not exist, create a new entry and initialize its occurrence count to 1.
[0046] Once the traversal is complete, the statistics structure will contain each color or hash value and the number of times it occurs.
[0047] It also includes optimization steps, specifically:
[0048] Select RGB color space to calculate the distance between colors;
[0049] Color distance calculation, calculate the distance between two colors. For RGB color space, the distance calculation formula is:
[0050]
[0051] Among them, R1, G1, B1 and R2, G2, B2 are the RGB values of two colors respectively;
[0052] Threshold setting: set the color distance threshold according to application requirements to determine whether two colors are similar;
[0053] Color merging, traverse all colors, for each color, check whether the distance between it and other colors is less than the threshold;
[0054] If the distance between two colors is less than the threshold, they are considered similar colors, merged into one color category, and the count of the color category in the color counter is updated;
[0055] The theme color is determined. After merging the colors, the color counter is traversed again to find the color category with the highest count, which is regarded as the theme color of the image.
[0056] It also includes verification steps, specifically:
[0057] Prepare verification tools and environment, select image editing software that supports color selection and comparison as the verification tool, prepare the original image to be verified and the theme color sample extracted from the image data;
[0058] Color comparison and verification, opening the original image in the image editing software;
[0059] Use the color picker tool to select the previously determined theme color in the software;
[0060] Observe and record the distribution of the theme color in the original image, and check whether it occupies the main part of the image or appears prominently in key areas;
[0061] Use the statistical function of the image editing software or a third-party tool to calculate the proportion of the theme color in the image, and compare this proportion with the theme color proportion obtained previously through pixel data analysis to verify their consistency or proximity;
[0062] Verify the result analysis: if the theme color is widely distributed in the image and accounts for a significant proportion, and is consistent with the previous pixel data analysis results, the verification is considered successful, confirming that the theme color does represent the main color in the image; if it is found that there is a significant difference in the color distribution between the theme color and the original image, or it is inconsistent with the previous analysis results, it is necessary to re-check the pixel data analysis process, or adjust the color merging threshold, and redefine the theme color.
[0063] A system for extracting the theme color of an image based on javascript, including the following modules:
[0064] The image loading module creates an Image object and is configured with an interface to receive and set the URL of the image resource to be processed to the src attribute of the Image object, thereby loading the image resource; a monitoring mechanism is provided, which is triggered in the onload event of the Image object to confirm that the loading of the image resource is complete;
[0065] The canvas and rendering module creates a canvas element and provides an interface to obtain the 2D rendering context object context of the canvas; uses the drawImage method of the context to draw the loaded image object onto the canvas;
[0066] The pixel data acquisition module extracts the pixel data of the image drawn on the canvas through the getImageData method of canvas. The pixel data is an array composed of rgba values, and each rgba value set contains four components: red R, green G, blue B and transparency alpha;
[0067] The color information processing module processes the acquired pixel data and divides each four consecutive RGBA values into a group, each group represents the color information of a pixel; it provides a color information statistics function to record and count the number of times each color information appears in the picture;
[0068] The theme color determination module traverses the color information statistics, identifies and extracts the color information with the most occurrences, marks the color information as the theme color of the picture, and provides an interface for external systems or components to call or display.
[0069] The system further includes a verification module, which specifically includes:
[0070] Verification preparation function, integrating or calling the image editing software interface that supports color selection and comparison for the subsequent color verification process; receiving and storing the original image to be verified and the theme color sample extracted by the system;
[0071] Color comparison and verification function, automatically or manually triggering the operation of opening the original image in the image editing software; using the color picker tool or integrated interface of the image editing software to select the theme color; analyzing and recording the distribution of the theme color in the original image, including its main occupied area and the significance of key areas in the image; if the image editing software or integrated interface supports it, calculating the proportion of the theme color in the image and comparing it with the theme color proportion previously obtained by the system through pixel data analysis to evaluate its consistency;
[0072] The verification result analysis function determines whether the theme color successfully represents the main color in the image based on the results of color comparison and verification; if the verification fails, that is, there is a significant difference in the color distribution between the theme color and the original image or it is inconsistent with the previous analysis results, it triggers an instruction to re-check the pixel data analysis process, or adjust the color merging threshold, and redetermine the theme color.
[0073] Compared with the prior art, the present invention has the following beneficial effects:
[0074] The method for extracting the theme color of a picture based on javascript in the present invention successfully realizes the accurate extraction of the theme color of the picture through javascript, a programming language with high popularity and excellent performance, avoids the dependence on external expensive tools or complex hardware, not only greatly reduces the cost, but also significantly improves the speed and efficiency of theme color extraction. The method can calculate the theme color of the picture in real time, and dynamically adjust the color value according to the characteristics of different pictures, achieves a high degree of flexibility and wide applicability, and effectively reduces the cost of configuration and adjustment. Especially in an environment with poor network conditions, the method can still quickly extract the theme color, and preferentially load it as the background color, which not only greatly speeds up the rendering speed of the page, but also effectively improves the user's visual experience and satisfaction. Users can enjoy a more harmonious, beautiful and personalized interface display, thereby further enhancing the attractiveness and market competitiveness of the product. BRIEF DESCRIPTION OF THE DRAWINGS
[0075] In order to more clearly illustrate the technical solutions of the embodiments of the present invention, the drawings required for use in the embodiments are briefly introduced below. It should be understood that the following drawings only show certain embodiments of the present invention and therefore should not be regarded as limiting the scope. For ordinary technicians in this field, other related drawings can be obtained based on these drawings without creative work.
[0076] Figure 1 The present invention is a flowchart of a method for extracting the theme color of an image based on javascript. DETAILED DESCRIPTION
[0077] In order to make the purpose, technical solutions and advantages of the embodiments of the present invention clearer, the technical solutions in the embodiments of the present invention will be clearly and completely described below in conjunction with the drawings in the embodiments of the present invention. Obviously, the described embodiments are part of the embodiments of the present invention, not all of the embodiments. Generally, the components of the embodiments of the present invention described and shown in the drawings here can be arranged and designed in various different configurations.
[0078] Therefore, the following detailed description of the embodiments of the present invention provided in the accompanying drawings is not intended to limit the scope of the invention claimed for protection, but merely represents selected embodiments of the present invention. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.
[0079] It should be noted that similar reference numerals and letters denote similar items in the following drawings, and therefore, once an item is defined in one drawing, further definition and explanation thereof is not required in subsequent drawings.
[0080] The present invention is further described in detail below in conjunction with the accompanying drawings:
[0081] See also Figure 1 , is a flow chart of a method for extracting the theme color of an image based on javascript in the present invention, comprising the following steps:
[0082] S1, create an Image object, and assign the image resource to be processed to the src attribute of the Image object to load the image resource. The creation of the Image object specifically includes the following steps:
[0083] S1.1, create an Image object using the new keyword in JavaScript to represent and display images on a Web page.
[0084] S1.2, assign the URL of the image resource to be processed to the src attribute of the created Image object to trigger the browser to load the image resource.
[0085] S1.3, using the onload event of the Image object, set the event processing function, which is called after the image resource is loaded.
[0086] S1.4. In the set event processing function, write the code logic after the image is loaded, and use the drawImage method of canvas to draw the loaded image onto the canvas.
[0087] S2, in the onload event of the Image object, obtain the loaded image object.
[0088] S3, create a canvas and obtain the 2D rendering context object context of the canvas.
[0089] S3.1, in HTML documents, by <canvas>The tag directly defines a canvas element with a unique id identifier, specified width and height, and then adds the canvas element to the document's DOM structure.
[0090] S3.2, if the canvas element has been defined in HTML, use the document.getElementById method and pass in the id identifier of the canvas element to obtain the element; if the canvas element is created dynamically, directly use the reference obtained when it is created.
[0091] S3.3, use the getContext('2d') method of the obtained canvas element to obtain a 2D rendering context object, which provides an API for drawing 2D graphics on the canvas.
[0092] S3.4, if the 2D rendering context object is successfully obtained, the API provided by the object is used to perform graphics drawing operations on the canvas.
[0093] S4, use the context's drawImage method to draw the obtained image object onto the canvas.
[0094] S5, through the getImageData method of canvas, obtain the pixel data of the image drawn on the canvas, and the pixel data is an array composed of RGBA values.
[0095] S5.1, determine a pixel data area to be obtained from the canvas, where the area is defined by a rectangle, specifically including the horizontal coordinate x of the upper left corner of the rectangle, the vertical coordinate of the upper left corner, the width of the rectangle, and the height of the rectangle; the rectangular area covers the entire canvas or a specific part of the canvas.
[0096] S5.2, call the getImageData method of the CanvasRenderingContext2D object and pass in four parameters of the determined rectangular area to obtain an ImageData object; the ImageData object returned by the getImageData method contains a data attribute array, and the elements in the array represent the RGBA values of each pixel in the specified area.
[0097] S5.3, obtain the data attribute of the obtained ImageData object to access the pixel data array; each pixel in the array consists of four consecutive elements, representing the values of red R, green G, blue B and transparency alpha, and the value range is 0 to 255.
[0098] S6, processing the acquired pixel data, dividing every four consecutive RGBA values into a group, representing the color information of the pixel.
[0099] S6.1, data preparation step, obtains a pixel data array containing color information of all pixels in the image from the ImageData object, where the color of each pixel is represented by four consecutive numerical values corresponding to the intensity of red R, green G, blue B and transparency alpha;
[0100] S6.2, initialization index step, setting an index variable for traversing the pixel data array, the index pointing to the first element of the array when initialized;
[0101] S6.3, group processing steps:
[0102] S6.3.1, index range check sub-step, before each iteration, ensure that the current value of the index variable plus 3 does not exceed the length of the pixel data array to avoid array out of bounds.
[0103] S6.3.2, RGBA value extraction sub-step, reads the values of the current index and the three positions after it from the array, and these four values represent the R, G, B, and A values of a pixel point respectively.
[0104] S6.3.3, group storage sub-step, regards the extracted four values as a group, representing the color information of a pixel, and stores this group of values in a new data structure as needed.
[0105] S6.3.4, index update sub-step: After each iteration, the index variable is increased by 4 to process the color information of the next pixel.
[0106] S6.3.5, iterate and repeat the sub-step, repeatedly execute the index range check sub-step, RGBA value extraction sub-step, group storage sub-step and index update sub-step until the index variable exceeds the length of the pixel data array, that is, the color information of all pixels is processed.
[0107] S7, counting the processed color information, and recording the number of times each color information appears.
[0108] S7.1, initialize the statistics structure and create a data structure to store each color and the number of times it appears.
[0109] S7.2, traverse the pixel data, traverse the pixel data array provided by the data attribute of the ImageData object, each pixel in the array consists of four consecutive elements, and process the elements one by one through a loop.
[0110] S7.3, Calculate color hash value, choose to use the hash value as the key, then define a function to calculate the hash value for a given RGBA value.
[0111] S7.4, update the statistical structure. For each pixel in the array, search for the corresponding entry in the statistical structure according to its RGBA value or the calculated hash value. If the entry exists, increase its occurrence count by 1; if the entry does not exist, create a new entry and initialize its occurrence count to 1.
[0112] S7.5, after the traversal is completed, the statistical structure will contain each color or hash value and the number of times it occurs.
[0113] S8, obtaining the color information with the most occurrences, which is the theme color of the picture.
[0114] S9 also includes optimization steps, specifically:
[0115] S9.1, select RGB color space to calculate the distance between colors.
[0116] S9.2, color distance calculation, calculate the distance between two colors. For the RGB color space, the distance calculation formula is:
[0117]
[0118] Among them, R1, G1, B1 and R2, G2, B2 are the RGB values of two colors respectively.
[0119] S9.3, threshold setting, sets the color distance threshold according to application requirements to determine whether two colors are similar.
[0120] S9.4, color merging, traverse all colors, for each color, check whether the distance between it and other colors is less than a threshold;
[0121] If the distance between two colors is less than a threshold, they are considered to be similar colors, merged into one color category, and the count of the color category in the color counter is updated.
[0122] S9.5, theme color determination, after merging the colors, re-traverse the color counters to find the color category with the highest count, and regard it as the theme color of the image.
[0123] S10, verification step, specifically:
[0124] S10.1, prepare verification tools and environment, select image editing software that supports color selection and comparison as verification tools, prepare the original image to be verified and the theme color sample extracted from the image data;
[0125] S10.2, color comparison and verification, opening the original image in the image editing software;
[0126] S10.3, use the color picker tool to select the previously determined theme color in the software;
[0127] S10.4, observe and record the distribution of the theme color in the original image, and check whether it occupies the main part of the image or appears prominently in the key area;
[0128] S10.5, using the statistical function of the image editing software or a third-party tool to calculate the proportion of the theme color in the image, and comparing this proportion with the proportion of the theme color obtained previously through pixel data analysis to verify their consistency or proximity;
[0129] S10.6, verification result analysis, if the theme color is widely distributed in the image and accounts for a significant proportion, and is consistent with the previous pixel data analysis results, then the verification is considered successful, confirming that the theme color does represent the main color in the image; if it is found that there is a significant difference in the color distribution between the theme color and the original image, or it is inconsistent with the previous analysis results, it is necessary to re-check the pixel data analysis process, or adjust the color merging threshold, and redetermine the theme color.
[0130] Example
[0131] The method for extracting the theme color of an image based on javascript in the present invention is specifically implemented as follows:
[0132] Step 1: Create an image
[0133] const img = new Image();
[0134] Assign image resources to the image tag
[0135] img.src = image;
[0136] After the image resource is loaded, the image object is obtained and used in step 2 to pass it into the canvas to obtain the corresponding pixel data
[0137] img.onload=()=>{
[0138] / / You can get the img object here
[0139] };
[0140] Step 2: Create a canvas
[0141] (1) Create a canvas context object context
[0142] const context=canvas.getContext("2d");
[0143] (2) Draw an image on the drawing board through context
[0144] context.drawImage(img,0,0);
[0145] The img in the drawImage method is the img object after onload in step 1
[0146] (3) Get pixel information through canvas's getImageData
[0147] let pixelData=context.getImageData(0,0,canvas.width,canvas.height).data;
[0148] PixelData is an array of rgba, which represents red, green, blue and alpha. Each pixel of the rgba image is represented by the above four values, that is, each four is a group.
[0149] Step 3: Process pixel data
[0150] (1) From step 2, we can see that pixelData is an array composed of rgba.
[0151] ①For example, the first 12 numbers are 0, 163, 248, 255, 0, 163, 248, 255, 0, 164, 249, 255;
[0152] ② Combine every four numbers into a group. For example, the first four numbers are 0, 163, 248, and 255 respectively; these four numbers can be marked as rgba(0,163,248,255), the next four numbers are 0, 163, 248, 255; similarly marked as rgba(0,163,248,255), the next four numbers are 0, 164, 249, 255; similarly marked as rgba(0,164,249,255);
[0153] ③ Carry out the same process for the subsequent numbers, and get a series of data like this: rgba(0,163,248,255), rgba(0,163,248,255), rgba(0,164,249,255), rgba(0,164,249,255)...
[0154] ④Then count the number of occurrences of a series of data.
[0155] Step 4: Get the color value that appears most times.
[0156] An embodiment of the present invention is a system for extracting the theme color of an image based on javascript, comprising the following modules:
[0157] The image loading module creates an Image object and is configured with an interface to receive and set the URL of the image resource to be processed to the src attribute of the Image object, thereby loading the image resource; a monitoring mechanism is provided, which is triggered in the onload event of the Image object to confirm that the loading of the image resource is complete;
[0158] The canvas and rendering module creates a canvas element and provides an interface to obtain the 2D rendering context object context of the canvas; uses the drawImage method of the context to draw the loaded image object onto the canvas;
[0159] The pixel data acquisition module extracts the pixel data of the image drawn on the canvas through the getImageData method of canvas. The pixel data is an array composed of rgba values, and each rgba value set contains four components: red R, green G, blue B and transparency alpha;
[0160] The color information processing module processes the acquired pixel data and divides each four consecutive RGBA values into a group, each group represents the color information of a pixel; it provides a color information statistics function to record and count the number of times each color information appears in the picture;
[0161] The theme color determination module traverses the color information statistics, identifies and extracts the color information with the most occurrences, marks the color information as the theme color of the picture, and provides an interface for external systems or components to call or display.
[0162] Verification module, the verification module specifically includes:
[0163] Verification preparation function, integrating or calling the image editing software interface that supports color selection and comparison for the subsequent color verification process; receiving and storing the original image to be verified and the theme color sample extracted by the system;
[0164] Color comparison and verification function, automatically or manually triggering the operation of opening the original image in the image editing software; using the color picker tool or integrated interface of the image editing software to select the theme color; analyzing and recording the distribution of the theme color in the original image, including its main occupied area and the significance of key areas in the image; if the image editing software or integrated interface supports it, calculating the proportion of the theme color in the image and comparing it with the theme color proportion previously obtained by the system through pixel data analysis to evaluate its consistency;
[0165] The verification result analysis function determines whether the theme color successfully represents the main color in the image based on the results of color comparison and verification; if the verification fails, that is, there is a significant difference in the color distribution between the theme color and the original image or it is inconsistent with the previous analysis results, it triggers an instruction to re-check the pixel data analysis process, or adjust the color merging threshold, and redetermine the theme color.
[0166] The above are only preferred embodiments of the present invention and are not intended to limit the present invention. For those skilled in the art, the present invention may have various modifications and variations. Any modification, equivalent replacement, improvement, etc. made within the spirit and principle of the present invention shall be included in the protection scope of the present invention.< / canvas> < / canvas>
Claims
1. A method for extracting the theme color of an image based on javascript, characterized in that: The following steps are involved: Create an Image object and assign the image resource to be processed to the src attribute of the Image object to load the image resource; In the onload event of the Image object, get the loaded image object; Create a canvas and get the 2D rendering context object context of the canvas; Use the context's drawImage method to draw the obtained image object onto the canvas; Get the pixel data of the image drawn on the canvas through the getImageData method of canvas. The pixel data is an array composed of RGBA values. Process the acquired pixel data and group every four consecutive RGBA values into a group to represent the color information of the pixel; Count the processed color information and record the number of times each color information appears; Get the color information that appears most times, which is the theme color of the image.
2. A method for extracting the theme color of an image based on javascript as claimed in claim 1, characterized in that: The creation of the Image object specifically includes the following steps: Use JavaScript's new keyword to create an Image object, which is used to represent and display images on a Web page. Assign the URL of the image resource to be processed to the src attribute of the created Image object to trigger the browser to load the image resource; Use the onload event of the Image object to set the event processing function, which is called after the image resource is loaded; In the set event handling function, write the code logic after the image is loaded, and use the drawImage method of canvas to draw the loaded image onto the canvas.
3. A method for extracting the theme color of an image based on javascript as claimed in claim 1, characterized in that: The process of creating a canvas and obtaining a 2D rendering context object context of the canvas specifically includes the following steps: In an HTML document, by <canvas> The tag directly defines a canvas element with a unique id identifier, specified width and height, and then adds the canvas element to the document's DOM structure;< / canvas> If the canvas element has been defined in HTML, use document.getElementById method and pass in the id identifier of the canvas element to get the element; if the canvas element is created dynamically, directly use the reference obtained when it was created; Use the getContext('2d') method of the obtained canvas element to obtain a 2D rendering context object, which provides an API for drawing 2D graphics on the canvas. If the 2D rendering context object is successfully obtained, the API provided by the object is used to perform graphics drawing operations on the canvas.
4. A method for extracting the theme color of an image based on javascript as claimed in claim 1, characterized in that: The pixel data of the image drawn on the canvas is obtained through the getImageData method of canvas. The specific steps are: Determine the pixel data area to be obtained from the canvas, where the area is defined by a rectangle, including the horizontal coordinate x of the upper left corner of the rectangle, the vertical coordinate of the upper left corner, the width of the rectangle, and the height of the rectangle; the rectangular area covers the entire canvas or a specific part of the canvas; Call the getImageData method of the CanvasRenderingContext2D object and pass in four parameters of the determined rectangular area to obtain an ImageData object; the ImageData object returned by the getImageData method contains a data attribute array, and the elements in the array represent the RGBA value of each pixel in the specified area; Get the data property of the obtained ImageData object to access the pixel data array; each pixel in the array consists of four consecutive elements, representing the values of red (R), green (G), blue (B), and transparency (alpha), and the value range is 0 to 255.
5. The method for extracting the theme color of an image based on javascript as claimed in claim 1, characterized in that: The pixel data is processed and every four consecutive RGBA values are grouped into one group, specifically: Data preparation step, get the pixel data array containing the color information of all pixels in the image from the ImageData object, where the color of each pixel is represented by four consecutive numerical values, corresponding to the intensity of red (R), green (G), blue (B), and transparency (alpha); Initialize the index step and set the index variable for traversing the pixel data array. When initialized, the index points to the first element of the array. Group processing steps: Index range check substep, before each iteration, ensure that the current value of the index variable plus 3 does not exceed the length of the pixel data array to avoid array out of bounds; The RGBA value extraction sub-step reads the values of the current index and the three positions after it from the array. These four values represent the R, G, B, and A values of a pixel point respectively. In the group storage sub-step, the four extracted values are regarded as a group representing the color information of a pixel, and the group of values is stored in a new data structure as needed; Index update sub-step: After each iteration, the index variable is increased by 4 to process the color information of the next pixel; Iterate and repeat the sub-step, repeatedly execute the index range check sub-step, RGBA value extraction sub-step, group storage sub-step and index update sub-step until the index variable exceeds the length of the pixel data array, that is, the color information of all pixels is processed.
6. A method for extracting the theme color of an image based on javascript as claimed in claim 1, characterized in that: The statistics of the processed color information are specifically as follows: Initialize the statistics structure and create a data structure to store each color and its number of occurrences; Iterate over the pixel data, iterate over the pixel data array provided by the data property of the ImageData object. Each pixel in the array consists of four consecutive elements, and the elements are processed one by one through a loop; Calculate the color hash value. If you choose to use the hash value as the key, define a function to calculate the hash value of a given RGBA value. Update the statistics structure. For each pixel in the array, find the corresponding entry in the statistics structure based on its RGBA value or the calculated hash value. If the entry exists, add 1 to its occurrence count. If the entry does not exist, create a new entry and initialize its occurrence count to 1; Once the traversal is complete, the statistics structure will contain each color or hash value and the number of times it occurs.
7. The method for extracting the theme color of an image based on javascript as claimed in claim 1, characterized in that: It also includes optimization steps, specifically: Select RGB color space to calculate the distance between colors; Color distance calculation, calculate the distance between two colors. For RGB color space, the distance calculation formula is: (1) Among them, R1, G1, B1 and R2, G2, B2 are the RGB values of two colors respectively; Threshold setting: set the color distance threshold according to application requirements to determine whether two colors are similar; Color merging, traverse all colors, for each color, check whether the distance between it and other colors is less than the threshold; If the distance between two colors is less than the threshold, they are considered similar colors, merged into one color category, and the count of the color category in the color counter is updated; The theme color is determined. After merging the colors, the color counter is traversed again to find the color category with the highest count, which is regarded as the theme color of the image.
8. The method for extracting the theme color of an image based on javascript as claimed in claim 1, characterized in that: It also includes verification steps, specifically: Prepare verification tools and environment, select image editing software that supports color selection and comparison as the verification tool, prepare the original image to be verified and the theme color sample extracted from the image data; Color comparison and verification, opening the original image in the image editing software; Use the color picker tool to select the previously determined theme color in the software; Observe and record the distribution of the theme color in the original image, and check whether it occupies the main part of the image or appears prominently in key areas; Use the statistical function of the image editing software or a third-party tool to calculate the proportion of the theme color in the image, and compare this proportion with the theme color proportion obtained previously through pixel data analysis to verify their consistency or proximity; Verify the result analysis: if the theme color is widely distributed in the image and accounts for a significant proportion, and is consistent with the previous pixel data analysis results, the verification is considered successful, confirming that the theme color does represent the main color in the image; if it is found that there is a significant difference in the color distribution between the theme color and the original image, or it is inconsistent with the previous analysis results, it is necessary to re-check the pixel data analysis process, or adjust the color merging threshold, and redefine the theme color.
9. A system for extracting the theme color of an image based on javascript, characterized in that: Includes the following modules: The image loading module creates an Image object and is configured with an interface to receive and set the URL of the image resource to be processed to the src attribute of the Image object, thereby loading the image resource; A monitoring mechanism is set up, which is triggered in the onload event of the Image object to confirm that the image resource has been loaded; The canvas and rendering module creates a canvas element and provides an interface to obtain the 2D rendering context object context of the canvas; uses the drawImage method of the context to draw the loaded image object onto the canvas; The pixel data acquisition module extracts the pixel data of the image drawn on the canvas through the getImageData method of canvas. The pixel data is an array composed of rgba values, and each rgba value set contains four components: red (R), green (G), blue (B) and transparency (alpha); The color information processing module processes the acquired pixel data and divides each four consecutive RGBA values into a group, each group represents the color information of a pixel; it provides a color information statistics function to record and count the number of times each color information appears in the picture; The theme color determination module traverses the color information statistics, identifies and extracts the color information with the most occurrences, marks the color information as the theme color of the picture, and provides an interface for external systems or components to call or display.
10. A system for extracting image theme colors based on javascript as claimed in claim 9, characterized in that: The system further includes a verification module, which specifically includes: Verification preparation function, integrating or calling the image editing software interface that supports color selection and comparison for the subsequent color verification process; receiving and storing the original image to be verified and the theme color sample extracted by the system; Color comparison and verification function, automatically or manually triggering the operation of opening the original image in the image editing software; using the color picker tool or integrated interface of the image editing software to select the theme color; analyzing and recording the distribution of the theme color in the original image, including its main occupied area and the significance of key areas in the image; if the image editing software or integrated interface supports it, calculating the proportion of the theme color in the image and comparing it with the theme color proportion previously obtained by the system through pixel data analysis to evaluate its consistency; The verification result analysis function determines whether the theme color successfully represents the main color in the image based on the results of color comparison and verification; if the verification fails, that is, there is a significant difference in the color distribution between the theme color and the original image or it is inconsistent with the previous analysis results, it triggers an instruction to re-check the pixel data analysis process, or adjust the color merging threshold, and redetermine the theme color.