0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

表示されている画像情報を取得

Posted at

Web上にある画像情報を取得して表示させます。

<img id="target" src="./images/img/apple.jpg" alt="リンゴ">
const element = document.getElementById("target");

const width = element.naturalWidth;
const height = element.naturalHeight;
const alt = element.getAttribute('alt')
const src = element.getAttribute('src')
const resultPath = src.split("/").reverse().slice(1).reverse().join("/");
const filename = src.split("/").reverse()[0].split('.')[0];
const extend = src.split("/").reverse()[0].split('.')[1];

console.log(`横:${width}px`)
console.log(`縦:${height}px`)
console.log(`Alt:${alt}`)
console.log(`パス:${resultPath}`)
console.log(`ファイル名${filename}`)
console.log(`拡張子${extend}`)

ファイルサイズや更新日はサーバーからのHTTPレスポンスデータから取得するみたい。

let lastModified = "";
let contentLength = "";

(async () => {
  const element = document.getElementById("target");

  const fetchImg = await fetchImage(element.src);
  await getData(fetchImg);

  console.log(`ファイルサイズ:${Math.floor(contentLength / 1024)}KB`)
  console.log(formatDate(lastModified))
})();

async function fetchImage(target) {
  const response = await fetch(target);
  return response;
}

function getData(target) {
  const headers = target.headers;
  for (var pair of headers.entries()) {
    if (pair[0] === "last-modified") {
      lastModified = pair[1];
    }
    if (pair[0] === "content-length") {
      contentLength = pair[1];
    }
  }
}

function formatDate(targetDate) {
  const modified = new Date(targetDate);
  const y = modified.getFullYear();
  const m = modified.getMonth() + 1;
  const d = modified.getDate();
  const h = modified.getHours();
  const min = modified.getMinutes();
  return `更新日:${y}${m}${d}${h}${min}分`;
};

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?