Convert pictures into character paintings through javascript
1. Get uploaded image object data
Javascript cannot directly obtain the data of locally uploaded images, and html5 can solve this problem. The FileReader interface in HTML5 can read the data of the image object into the memory, and then access the data through the progress events (Progress Events) of the interface.
Browser support:
1. Internet Explorer: 10
2. Firefox: 10
3. Chrome: 13
4. Opera: 12
5. Safari: partial
2. Get the pixels of the image object
The getImageData method of the image object returns an object. The rgba value of each pixel is stored under its data attribute. This is a one-bit array, that is, rgba respectively. Corresponds to a value, and then follows the rgba of the pixel. Assuming that the value of getImageData.data is [1,2,3,4,5,6,7,8], then the getImageData object range contains 2 pixels. The rgba values of the first pixel are 1,2,3,4 respectively, and the rgba values of the second pixel are 4,5,6,7,8. Therefore, when we get the rgba value of each pixel, its index should be multiplied by 4 on the index value of the pixel, and then calculate the grayscale through getGray().
3. Calculate grayscale based on rgb value
Different RGB spaces have different calculation formulas for grayscale. The formulas for calculating grayscale in several common RGB spaces are as follows:
1. Simplified sRGB IEC61966 -2.1 [gamma=2.20]
Gray = (R^2.2 * 0.2126 G^2.2 * 0.7152 B^2.2 * 0.0722)^(1/2.2)
2. Adobe RGB (1998) [gamma=2.20]
Gray = (R^2.2 * 0.2973 G^2.2 * 0.6274 B^2.2 * 0.0753)^(1/2.2)
3. Apple RGB [gamma=1.80]
Gray = (R^1.8 * 0.2446 G^1.8 * 0.6720 B^1.8 * 0.0833)^(1/1.8)
4. ColorMatch RGB [gamma=1.8]
Gray = (R^1.8 * 0.2750 G^1.8 * 0.6581 B^1.8 * 0.0670)^(1/1.8)
5. Simplified KODAK DC Series Digital Camera [gamma=2.2]
Gray = (R^2.2 * 0.2229 G^2.2 * 0.7175 B^2.2 * 0.0595)^(1/ 2.2)
4. Generate corresponding characters based on grayscale
Replace different grayscales with corresponding characters. In principle, pixels with darker grayscale should use more complex characters. Specific characters can be freely replaced. This is just a Test version.
Code snippet: