【问题标题】:How can I read metadata of PNG in react如何在反应中读取 PNG 的元数据
【发布时间】:2021-05-02 22:30:54
【问题描述】:

png 中有 json 数据,我想读取 PNG 文件中的元数据。 我正在使用 reactjs。 上传图片文件后,有什么想法吗?

import React, { useState } from 'react'
import {Typography, Button, Form, Input} from 'antd';
import Axios from 'axios';

function test() { 
    const [imgBase64, setImgBase64] = useState(""); 
    const [imgages, setImages] = useState([]);      
    
    const fileupload = (event) => {
      const readit = new FileReader();
  
      reader.onloadend = () => {
        const base64 = readit.result;
        if (base64) {
          setImgBase64(base64.toString()); 
        }
      }
      if (event.target.files[0]) {
        readit.readAsDataURL(event.target.files[0]); 
        setImages(event.target.files[0]); 
        console.log(event.target.files[0]);
      }
    }
    
    return (
        <div style={{"backgroundColor": "#ffffff", "width":"100px", "height" : "100px"}}>
        </div>
          <input type="file" onChange={fileupload}/>
        </div>
      </div>
    );
  }

export default test

【问题讨论】:

    标签: reactjs image png metadata reader


    【解决方案1】:

    你可以使用这个库:https://github.com/hometlt/png-metadata

    这是一个例子:

        function loadFileAsBlob(url){
            return new Promise((resolve, reject) => {
              var xhr = new XMLHttpRequest();
              xhr.open('GET', url, true);
              xhr.responseType = 'blob';
              xhr.onload = function(e) {
                if (this.status === 200) {
                  resolve(this.response);
                  // myBlob is now the blob that the object URL pointed to.
                }else{
                  reject(this.response);
                }
              };
              xhr.send();
            })
          };
    
      //Browser
      const blob = await loadFileAsBlob('1000ppcm.png');
      const buffer = await blob.arrayBuffer();
    
    
      //read metadata
      metadata = readMetadata(buffer);
    

    以及你会得到的数据格式:

    {
      "pHYs": { 
        "x": 30000,
        "y": 30000,
        "units": RESOLUTION_UNITS.INCHES
      },
      "tEXt": {
        "Title":            "Short (one line) title or caption for image",
        "Author":           "Name of image's creator",
        "Description":      "Description of image (possibly long)",
        "Copyright":        "Copyright notice",
        "Software":         "Software used to create the image",
        "Disclaimer":       "Legal disclaimer",
        "Warning":          "Warning of nature of content",
        "Source":           "Device used to create the image",
        "Comment":          "Miscellaneous comment"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-12
      • 2016-04-29
      • 2012-11-15
      • 2011-05-04
      • 2017-05-07
      • 2021-01-06
      • 2020-03-31
      • 1970-01-01
      • 2012-12-14
      相关资源
      最近更新 更多