我正在使用Chrome擴展程序,在其中調整用戶右鍵單擊的圖像大小(實際調整大小;不更改瀏覽器顯示)。當他們右擊圖像時,我可以訪問圖像的'src'。如何在JavaScript中獲取圖像/ blob的MIME類型?
我可以調整非GIF圖像的大小;我使用畫布來做到這一點。你可以看到我在這裏做這個https://jsfiddle.net/cyqvacc6/6/。
img_url = 'https://i.imgur.com/SHo6Fub.jpg';
function get_image(image_url, emoji_name) {
var img_el = document.createElement('img');
img_el.onload = function() {
canvas = img_to_canvas(img_el);
emoji_sized_canvas = emoji_sized(canvas);
document.body.appendChild(emoji_sized_canvas);
};
img_el.src = image_url;
}
function img_to_canvas(img) {
canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas_ctx = canvas.getContext('2d');
canvas_ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
return canvas;
}
function emoji_sized(canvas) {
var target_dim = emoji_dimensions(canvas.width, canvas.height);
var factor = 2;
var canvas_long_side = Math.max(canvas.width, canvas.height);
var target_long_side = Math.max(target_dim.width, target_dim.height);
new_canvas = document.createElement('canvas');
new_canvas_ctx = new_canvas.getContext('2d');
if ((target_long_side === canvas_long_side)) {
// Return the image.
return canvas;
} else if (target_long_side > canvas_long_side * factor) {
// Increase the size of the image and then resize the result.
new_canvas.width = canvas.width * factor;
new_canvas.height = canvas.height * factor;
new_canvas_ctx.drawImage(canvas, 0, 0, new_canvas.width, new_canvas.height);
return emoji_sized(new_canvas);
} else if (canvas_long_side > target_long_side * factor) {
// Half the size of the image and then resize the result.
var width = new_canvas.width = canvas.width/factor;
var height = new_canvas.height = canvas.height/factor;
new_canvas_ctx.drawImage(canvas, 0, 0, new_canvas.width, new_canvas.height);
return emoji_sized(new_canvas);
} else {
// Resize the image in one shot
new_canvas.width = target_dim.width;
new_canvas.height = target_dim.height;
new_canvas_ctx.drawImage(canvas, 0, 0, new_canvas.width, new_canvas.height);
return new_canvas;
}
}
function emoji_dimensions(width, height) {
const MAX_SIDE_LENGTH = 128;
// Get the larger side
long_side = Math.max(height, width);
// Determine the scale ratio
// If the image is between 95% to 100% of the target
// emoji size, don't adjust it's size.
var scale;
if ((long_side >= 0.95 * MAX_SIDE_LENGTH) && (long_side <= MAX_SIDE_LENGTH))
{
scale = 1;
} else {
scale = MAX_SIDE_LENGTH/long_side;
}
return {
'height': height * scale,
'width': width * scale
};
}
不幸的是,我沒有看到使用畫布調整GIF尺寸的簡單方法。當我在gif上嘗試相同的方法時,「調整大小」的圖像不再是gif;這只是gif調整後的第一幀。
我想我最終會發送GIF到服務器來調整它們的大小,但是爲了做到這一點,我需要知道我正在處理的圖像是否是動畫的,而我不知道該怎麼辦。
那麼,如何確定圖像是否爲gif?另外,是否可以從客戶端調整這些gif,即javascript?
作爲參考,我需要在字節大小和像素方面減少gif,即gif的高度和寬度都需要低於128像素,總字節大小小於64k。