在从相机或图库中拿起任何照片后,我将使用下一个功能。我正在使用插件cordova-plugin-simple-image-resizer
function resizeImageIfNeeded (imageUri, callback) {
// if image larger than this, resize
var MAX_IMG_FILE_SIZE = 307200 // 300kb
app.functions.getFileSize(imageUri, function (fileSize, err) {
if (!err && fileSize && fileSize < MAX_IMG_FILE_SIZE) {
// no need to resize image, return image unchanged
console.log('Image Not resized (file already small): ' + imageUri)
callback(imageUri)
} else {
// resize image (try even if file size is not obtained)
resizeImage(imageUri, function (resizedImageUri, err) {
if (err) {
// could not resize image
callback(imageUri, Error(err))
}
// return resized image
callback(resizedImageUri)
})
}
})
}
function resizeImage (imageUri, callback) {
// get just fileName with suffix, ex.: "photo1_resized.jpg"
var fileNameResized = addSuffixToFileName(
getFilenameFromURL(imageUri)[1],
'_resized'
)
var resizeOptions = {
uri: imageUri,
fileName: fileNameResized,
quality: 90,
width: 1200,
height: 1200,
base64: false
}
window.ImageResizer.resize(resizeOptions,
function (resizedImageUri) {
// success on resizing
console.log('%c Image resized: ', 'color: green; font-weight:bold', resizedImageUri)
callback(resizedImageUri)
},
// failed to resize
function (err) {
console.log('%c Failed to resize: ', 'color: red; font-weight:bold')
callback(imageUri, Error(err))
})
}
function getFileSize (fileUri, callback) {
var fileSize = null
window.resolveLocalFileSystemURL(fileUri, function (fileEntry) {
fileEntry.file(function (fileObj) {
fileSize = fileObj.size
callback(fileSize)
},
function (err) {
console.error('fileEntry error:\n', JSON.stringify(err))
callback(fileSize, Error(err))
})
},
function (err) {
console.error('resolveLocalFileSystemURL error:\n', JSON.stringify(err))
callback(fileSize, Error(err))
})
}
// ex: from "file:///storage/emulated/0/Android/data/com.form.parking.violation/cache/1525698243664.jpg"
// output[0] == "file:///storage/emulated/0/Android/data/com.form.parking.violation/cache"
// output[1] == "1525698243664.jpg"
function getFilenameFromURL (url) {
if (!url) {
return false
}
var output = []
output[1] = url.split('/').pop()
output[0] = url.substring(0, url.length - output[1].length - 1)
return output
}