Skip to content

Instantly share code, notes, and snippets.

@chingov
Created June 1, 2019 16:58
Show Gist options
  • Save chingov/9c2add5444913ed99b63945e7783ea16 to your computer and use it in GitHub Desktop.
Save chingov/9c2add5444913ed99b63945e7783ea16 to your computer and use it in GitHub Desktop.
[hexo_resize_image.js] Hexo博客框架中处理图片大小的js #Hexo #图片大小
function set_image_size(image, width, height)
{
image.setAttribute("width", width + "px");
image.setAttribute("height", height + "px");
}
function hexo_resize_image()
{
var imgs = document.getElementsByTagName('img');
for (var i = imgs.length - 1; i >= 0; i--)
{
var img = imgs[i];
var src = img.getAttribute('src').toString();
var fields = src.match(/\?(\d*x\d*)/);
if (fields && fields.length > 1)
{
var values = fields[1].split("x");
if (values.length == 2)
{
var width = values[0];
var height = values[1];
if (!(width.length && height.length))
{
var n_width = img.naturalWidth;
var n_height = img.naturalHeight;
if (width.length > 0)
{
height = n_height*width/n_width;
}
if (height.length > 0)
{
width = n_width*height/n_height;
}
}
set_image_size(img, width, height);
}
continue;
}
fields = src.match(/\?(\d*)/);
if (fields && fields.length > 1)
{
var scale = parseFloat(fields[1].toString());
var width = scale/100.0*img.naturalWidth;
var height = scale/100.0*img.naturalHeight;
set_image_size(img, width, height);
}
}
}
window.onload = hexo_resize_image;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment