[javascript] コピペで張り付けられた画像ファイルをアップロード前にリサイズする

javascriptでコピペで張り付けられた画像ファイルをアップロード前にリサイズするコードは以下の通り

$("textarea[name='msg']").on('paste', function(event){
 // event からクリップボードのアイテムを取り出す
 var items = (event.clipboardData || event.originalEvent.clipboardData).items; // ここがミソ
 for (var i = 0 ; i < items.length ; i++) {
 var item = items[i];
 if (item.type.indexOf("image") != -1) {
 // 画像データがあればページに添付する
 var image = item.getAsFile();
 makeSmall(image);
 }
 }
});

function getCurrentTime() {
 var now = new Date();
 var res = "" + now.getFullYear() + padZero(now.getMonth() + 1) + 
 padZero(now.getDate()) + "-" + padZero(now.getHours()) + 
 padZero(now.getMinutes()) + padZero(now.getSeconds());
 return res;
}

//先頭ゼロ付加
function padZero(num) {
 var result;
 if (num < 10) {
 result = "0" + num;
 } else {
 result = "" + num;
 }
 return result;
}

function makeSmall(file){
 
const THUMBNAIL_WIDTH = 900; // 画像リサイズ後の横の長さの最大値
const THUMBNAIL_HEIGHT = 900; // 画像リサイズ後の縦の長さの最大値
 
let reader = new FileReader();
 reader.readAsDataURL(file);
 reader.onload = (e) => {

 let img = new Image();
 img.onload = () => {

 var width, height;
 if(img.width > img.height){
 // 横長の画像は横のサイズを指定値にあわせる
 var ratio = img.height/img.width;
 width = THUMBNAIL_WIDTH;
 height = THUMBNAIL_WIDTH * ratio;
 } else {
 // 縦長の画像は縦のサイズを指定値にあわせる
 var ratio = img.width/img.height;
 width = THUMBNAIL_HEIGHT * ratio;
 height = THUMBNAIL_HEIGHT;
 }

 if(width > this.maxWidth) {

 height = Math.round(height * this.maxWidth / width);
 width = this.maxWidth;

 }

 let canvas = document.createElement('canvas');
 canvas.width = width;
 canvas.height = height;
 let ctx = canvas.getContext('2d');
 ctx.drawImage(img, 0, 0, width, height);
 ctx.canvas.toBlob((blob) => {

 const imageFile = new File([blob], file.name, {
 type: file.type,
 lastModified: Date.now()
 });
 //この後imageFileをアップロードすればよい; 

 }, file.type, 1);

 };
 img.src = e.target.result;

 };
 
}

上記のコードでは、Nameがmsgになっているテキストエリア上で画像をペーストすると、自動的に横幅もしくは縦幅900pxに修正してからアップロードするようになっている。

 

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です