使用 Phonegap (javascript),我试图缩小用户从他的画廊中选择的图像并将其复制到另一个文件夹结构。
我一直在尝试我能想到的一切,但我的想法已经不多了。我知道那里有几个类似的问题,但没有一个对我有用。
方法一
尝试从画布对象中获取图像并使用 PhoneGap 将其存储在手机的本地存储中。这是因为我保存了一个图像,但它已损坏。我尝试了很多不同的方法。我尝试过使用Uint8Array
、atob
转换等。请参阅下面的一些代码。
方法二
尝试使用 copyTo 功能。但是,我有两个问题。1)我不想要全尺寸图像(占用太多存储空间) 2)由于某种原因,我正在复制的对象总是 0 字节。
这是一些主要代码,请帮助。
function gotFileEntry(fe, file, type) {
alert("gotFileEntry: " + file.size);
// copy file
fe.file(function (f) { alert(f.size); }, function (e) { alert(e.code); });
fe.copyTo(dirImg, "copy.jpg", function(f) {alert("successful copy: " + f.fullPath);}, null);
var reader = new FileReader();
reader.onloadend = function (event) {
// shrink image
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = document.createElement('img');
img.src = reader.result;
img.onload = function () {
var newWidth = $(".page").width() * .8;
var newHeight = img.height / img.width * newWidth;
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, newWidth, newHeight);
// use setTimeout to allow the canvas to finish drawing
setTimeout(function () {
var shrunkImg = canvasToData(type, canvas); //canvas.toDataURL('image/jpeg');
// save image data to the phone storage
var imgData64 = canvas.toDataURL("image/png").replace(/data:image\/png;base64,/, ''); //canvas.toDataURL("image/png");//.replace("image/png", "image/octet-stream");
setTimeout(function () {
dirImg.getFile("test.png", { create: true, exclusive: false }, function (f) { getWin(imgData64, f); }, getFail);
//dirImg.getFile(file.name, { create: true, exclusive: false }, function (f) { getWin(imgData, f); }, getFail);
}, 0);
setTimeout(function () {
// returns data as Uint8Array array
var data = Base64Binary.decode(imgData64);
dirImg.getFile("test2.png", { create: true, exclusive: false }, function (f) { getWin(data, f); }, getFail);
//dirImg.getFile(file.name, { create: true, exclusive: false }, function (f) { getWin(imgData, f); }, getFail);
}, 0);
//var uintArray = Base64Binary.decode(data);
//fe.createWriter(gotFileWriter, function (error) { alert("CreateWriter failed: " + error.code); });
// Save the image path to the database
editCardView.card().UpdateImagePath(fe.fullPath);
// Display the image
$("#imgDisplay").attr({ "src": shrunkImg });
}, 0)
}
};
reader.onerror = function (event) {
errorHandler2(event.target.error.code);
};
reader.readAsDataURL(file);
}
function getWin(data, f) { f.createWriter(function(w) { writeWin(data, w); }, writeFail); };
function writeWin(data, writer) {
writer.write(data);
//writer.write(atob(data64));
};