Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to cache data through the RGBA value of png diagram in html5

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to cache data through the RGBA value of the png chart in html5". In the daily operation, I believe that many people have doubts about how to cache data through the RGBA value of the png chart in html5. The editor consulted all kinds of materials and sorted out a simple and useful operation method. I hope it will be helpful to answer the doubt of "how to cache data through the RGBA value of the png chart in html5". Next, please follow the editor to study!

Principle

We know that by setting Cache-Control and Expires response headers for static resources, browsers can be forced to cache them. When the browser makes a request to the background, it will first look in its own cache, and if it is not in the cache, it will continue to request this static resource from the server. Using this, we can store some information that needs to be cached through this static resource caching mechanism.

So how do we write information to static resources? canvas provides .getImageData () method and .createImageData () method, which can be used to read and set the RGBA value of the picture, respectively. So we can use these two API to read and write information.

Next, take a look at the schematic:

When a static resource enters the cache, any subsequent requests for the image will first look for the local cache, which means that the information has actually been cached locally in the form of a picture.

Note that since the rgba value can only be an integer between [0,255], the method discussed in this article applies only to data consisting of pure numbers.

Static server

Let's build a simple static server using node:

Const fs = require ('fs') const http = require (' http') const url = require ('url') const querystring = require (' querystring') const util = require ('util') const server = http.createServer ((req, res) = > {let pathname = url.parse (req.url). Pathname let realPath =' assets' + pathname console.log (realPath) if (realPath! = = 'assets/upload') {fs.readFile (realPath, binary, function (err) File) {if (err) {res.writeHead (500,{ 'Content-Type':' text/plain'}) res.end (err)} else {res.writeHead (200,{ 'Access-Control-Allow-Origin':' *', 'Content-Type':' image/png', 'ETag': "666666" 'Cache-Control':' public, max-age=31536000', 'Expires':' Mon, 07 Sep 2026 09:32:27 GMT'}) res.write (file, "binary") res.end ()}}) else {let post =''req.on (' data'') (chunk) = > {post + = chunk}) req.on ('end', () = > {post = querystring.parse (post) console.log (post.imgData) res.writeHead (200,{' Access-Control-Allow-Origin':'*'}) let base64Data = post.imgData.replace (/ ^ data:image\ /\ w +) Base64,/, "") let dataBuffer = new Buffer (base64Data, 'base64') fs.writeFile (' assets/out.png', dataBuffer (err) = > {if (err) {res.write (err) res.end ()} res.write ('OK') res.end ()})}) server.listen (80) console.log (' Listening on port: 80')

The function of this static resource is very simple, it provides two functions: generate the image through the base64 sent from the client and save it to the server; set the caching time of the image and send it to the client.

The key part is to set the response header:

Res.writeHead (200,{ 'Access-Control-Allow-Origin':' *', 'Content-Type':' image/png', 'ETag': "666666",' Cache-Control': 'public, max-age=31536000',' Expires': 'Mon, 07 Sep 2026 09:32:27 GMT'})

We set an one-year Content-Type and a ten-year Expires for this picture, which is long enough in theory. Let's do coding on the client side.

Client

Suppose we need to store 32-bit data, so we set the width to 8 and the height to 1 for canvas. The reason why 32-bit data corresponds to a length of 8 is that each pixel has a rgba, corresponding to red,green,blue and alpha4 values, so it needs to be divided by 4.

Let keyString = '01234567890123456789012345678901' let canvas = document.querySelector (' # canvas') let ctx = canvas.getContext ('2d') let imgData = ctx.createImageData (8,1) for (let I = 0; I

< imgData.data.length; i += 4) { imgData.data[i + 0] = parseInt(keyString[i]) + 50 imgData.data[i + 1] = parseInt(keyString[i + 1]) + 100 imgData.data[i + 2] = parseInt(keyString[i + 2]) + 150 imgData.data[i + 3] = parseInt(keyString[i + 3]) + 200 } ctx.putImageData(imgData, 0, 0) 首先我们假设需要被缓存的字符串为32位的01234567890123456789012345678901,然后我们使用.createImageData(8, 1)生成一个空白的imgData对象。接下来,我们对这个空对象进行赋值。为了实验效果更加直观,我们对rgba值都进行了放大。设置完了imgData以后,通过.putImageData()方法把它放入我们的canvas即可。 我们现在可以打印一下,看看这个imgData是什么: // console.log(imgData.data) [50, 101, 152, 203, 54, 105, 156, 207, 58, 109, 150, 201, 52, 103, 154, 205, 56, 107, 158, 209, 50, 101, 152, 203, 54, 105, 156, 207, 58, 109, 150, 201] 接下来,我们要把这个canvas编译为一张图片的base64并发送给服务器,同时接收服务器的响应,对图片进行缓存: $.post('http://xx.xx.xx.xx:80/upload', { imgData: canvas.toDataURL() }, (data) =>

{if (data = 'OK') {let img = new Image () img.crossOrigin = "anonymous" img.src =' http://xx.xx.xx.xx:80/out.png' img.onload = () = > {console.log ('complete picture request and cache') ctx.drawImage (img, 0, 0) console.log (ctx.getImageData (0,0,8) 1) .data)})

The code is simple. The base64 is sent to the server through the .toDataURL () method, and the server processes it and generates the picture and returns it. The address of the image resource is http://xx.xx.xx.xx:80/out.png. After img.onload, the image has already been cached locally. In this event, we print out the image information as a comparison with the source data.

Result analysis

Enable the server and run the client. When loading for * times, you can see the image information of the response through the console:

200OK, which is proved to be the picture obtained from the server.

Close the current page and reload:

200OK (from cache), which proves to be a picture read from the local cache.

Let's look directly at the comparison of RGBA values:

Source data: [50, 101, 152, 203, 54, 105, 156, 207, 58, 109, 150, 201, 52, 103, 154, 205, 56, 107, 158, 209, 50, 101, 152, 203, 54, 105, 152, 207, 58, 109, 150, 201] cached data: [50, 100, 152, 245, 54, 105, 157, 246, 57, 109, 149, 244, 52, 103, 154, 245, 56, 107, 157, 247, 50, 100, 152, 245, 54, 105, 157. 246, 57, 109, 149, 244]

According to the previous conclusion, the reason for the error between the source data and the cache data is determined to be caused by the interference of the alpha value. If we directly set the alpha value to 255 and only store the data inside the RGB value, the error can be eliminated. Here are the results of the improvement:

Source data: [0, 1, 2, 255, 4, 5, 6, 255, 8, 9, 0, 255, 2, 3, 4, 255, 6, 7, 8, 255, 0, 1, 2, 255, 4, 2, 255, 4, 5, 255] cached data: [0, 1, 2, 255, 4, 5, 5, 6, 255, 8, 9, 0, 255, 2, 3, 4, 255, 6, 7, 8, 255, 0, 1, 2, 255, 4, 5, 6. 255, 8, 9, 0, 255] so far The study on "how to cache data through the RGBA value of the png graph in html5" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report