简体   繁体   English

在浏览器中的 React 中将 base64 编码的 jpeg 转换为 png

[英]Converting a base64-encoded jpeg to a png in React in browser

I have a base64-encoded jpeg string that I'm holding in state in React.我有一个 base64 编码的 jpeg 字符串,我在 React 中保持它的状态。 I've been trying to work out how to convert it to a png format base64 string browser-side.我一直在努力研究如何将其转换为 png 格式的 base64 字符串浏览器端。

I briefly looked at sharp , but I found that requires a server side node.js environment.我简要地查看了sharp ,但我发现它需要一个服务器端node.js 环境。 I don't really want to have to write my own conversion script.我真的不想编写自己的转换脚本。 Further searching on npm hasn't yielded anything for me.对 npm 的进一步搜索对我没有任何帮助。

Any help with this is very much appreciated.非常感谢您对此的任何帮助。

This is untested, but you should be able to set the base64 JPEG as the source of an image, then draw that image to a canvas using context.drawImage ; 这未经测试,但是您应该能够将base64 JPEG设置为图像源,然后使用context.drawImage将该图像绘制到画布上; once it's on a canvas, you can use canvas.toDataURL() to get a base64 PNG of it. 将其放在画布上后,您可以使用canvas.toDataURL()获取它的base64 PNG。

You can use the base64 image to display your image without converting it. 您可以使用base64图像来显示图像而不进行转换。

See this answer for a reference 请参阅此答案以供参考

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM