自分用
詰め込みすぎだけど色々なアプリで使うため
<input type="file" accept="image/*" style="display:none;" @change="upload"/>
<canvas id="canvas" hidden></canvas>
upload(ev) {
// 画像一辺のサイズ指定
const TRIM_SIZE = 512
let blob = null
if (!ev) return
const file = ev.target.files[0]
// データのバリデーション
if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
return
}
const image = new Image()
const reader = new FileReader()
//画像ファイル読み込み
reader.onload = e => {
image.onload = () => {
//トリムの実行
let width, height, xOffset, yOffset
if (image.width > image.height) {
height = TRIM_SIZE
width = image.width * (TRIM_SIZE / image.height)
xOffset = -(width - TRIM_SIZE) / 2
yOffset = 0
} else {
width = TRIM_SIZE
height = image.height * (TRIM_SIZE / image.width)
yOffset = -(height - TRIM_SIZE) / 2
xOffset = 0
}
//canvasへ反映
const canvas = $('#canvas')
.attr('width', TRIM_SIZE)
.attr('height', TRIM_SIZE)
const ctx = canvas[0].getContext('2d')
ctx.clearRect(0, 0, width, height)
//EXIF情報の修正
let orientation = ''
EXIF.getData(file, () => {
orientation = file.exifdata.Orientation
switch (orientation) {
case 3: // 画像が180度回転している時
canvas.width = image.width
canvas.height = image.height
ctx.rotate(Math.PI)
ctx.drawImage(image, -image.width, -image.height)
ctx.rotate(-Math.PI)
break
case 6: // 画像が時計回りに90度回っている時
canvas.width = image.height
canvas.height = image.width
ctx.rotate(Math.PI * 0.5)
ctx.drawImage(image, 0, -image.height)
ctx.rotate(-Math.PI * 0.5)
break
case 8: // 画像が反時計回りに90度回っている時
canvas.width = image.height
canvas.height = image.width
ctx.rotate(-Math.PI * 0.5)
ctx.drawImage(image, -image.width, 0)
ctx.rotate(Math.PI * 0.5)
break
default: //回転していないときはそのまま
canvas.width = image.width
canvas.height = image.height
ctx.drawImage(image, 0, 0)
}
ctx.drawImage(image, xOffset, yOffset, width, height)
//base64へ変換
const base64 = canvas.get(0).toDataURL('image/jpeg')
const bin = atob(base64.split('base64,')[1])
const len = bin.length
const barr = new Uint8Array(len)
let i = 0
while (i < len) {
barr[i] = bin.charCodeAt(i)
i += 1
}
blob = new Blob([barr], { type: 'image/jpeg' })
ctx.clearRect(0, 0, width, height)
//firebaseへアップロード
const storageRef = firebase.storage().ref()
const uploadRef = storageRef.child(//パス
)
uploadRef.put(blob).then(() => {
uploadRef.getDownloadURL().then(url => {
//URLをどうにかする処理
})
})
})
}
image.src = e.target.result
}
reader.readAsDataURL(file)
},