将图像从 Html5 画布保存到手机存储
Saving image from Html5 canvas to phone storage
使用Phonegap(javascript),我正在尝试缩小用户从他的图库中选择的图像并将其复制到另一个文件夹结构中。
我一直在尝试我能想到的一切,但已经没有想法了。我知道有几个类似的问题,但没有一个对我有用。
方法 1
尝试从画布对象获取图像,并使用 PhoneGap 将其存储在手机的本地存储中。这在我保存图像时有效,但它已损坏。我尝试了很多不同的方法。我尝试使用Uint8Array
,atob
转换等。请参阅下面的一些代码。
方法 2
尝试使用 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));
};
试试这个插件,它对我有用。 将画布 base64 保存到 SD 卡上的图像
<head>
<title>
Hello World
</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0,
width=device-width, height=device-height, target-densitydpi=device-dpi" />
<script type="text/javascript" src="phonegap.js">
</script>
<script type="text/javascript">
//Base64code indicate about our canvas base64.
var Base64code = "iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAgAElEQVR42sS9d5xl11Xn+937hJtj5djVObdaauVkWZIt29gYbDlhjHkwJANDmmGY8ObBzGMew4c3MDAwQ3jYfgYeOQx4HL";
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
cordova.exec(function(winParam) {
console.log(winParam)
}, function(error) {}, "Base64toImagePlugin", "base64Data", [Base64code]);
}
</script>
</head>
<body>
</body>
插件类名的Java代码:Base64toImagePlugin.java
package com.inic.base64toimage.Plugin;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by ind652 on 08/10/13.
*/
public class Base64toImagePlugin extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("base64Data")) {
Log.i("BASE64DATA", "FastCanvas queueing set background color " + args.getString(0));
byte[] imageAsBytes = Base64.decode(args.getString(0).getBytes(), 0);
Bitmap b= BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
storeImage(b,"amitd.png");
return true;
}else{
return false;
}
}
private boolean storeImage(Bitmap imageData, String filename) {
//get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/myAppDir/amit/";
File sdIconStorageDir = new File(iconsStoragePath);
//create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
String filePath = sdIconStorageDir.toString() + filename;
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
//choose another format if PNG doesn't suit you
imageData.compress(Bitmap.CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
// Log.i("TAG", "Error saving image file: " + e.getMessage());
return false;
} catch (IOException e) {
// Log.i("TAG", "Error saving image file: " + e.getMessage());
return false;
}
return true;
}
}
配置.xml:
com.inic.base64toimage.Plugin 是包名称,您可以在其中创建插件类
<feature name="Base64toImagePlugin">
<param name="android-package" value="com.inic.base64toimage.Plugin.Base64toImagePlugin" />
</feature>
相关文章:
- 如何将getJson的响应保存在全局变量中
- 按下按钮时保存cookie
- 如何使用 Angular JS 将数据保存在数据库中
- 子字符串/正则表达式以获取字符串中保存的 SRC 值
- HTML5在画布中加载较小的图像并保存实际大小的图像
- 是否可以在浏览器中使用纯JavaScript保存音频流
- 如何将多个画布保存为一个图像
- 从手机中选择多个图像'使用phonegap的多媒体资料
- PHP:显示sqlite数据库中的html格式数据,使用tinymce保存
- 如何将乳胶配方奶粉图像保存到Asp.net中的文件夹中
- 保存数组javascript
- 如何使用手机浏览器上的按钮拨打USSD代码
- 是否可以在系统/电脑浏览器中访问手机摄像头
- 保存串行端口列表与流星
- 将JavaScript变量保存到Rails模型
- Java脚本将URL转换为已保存的URL时出错
- 将图像从 Html5 画布保存到手机存储
- 如何将图像从网站保存到手机相册
- 允许手机用户在不使用应用程序的情况下将文件从我的网站保存到他们的手机存储中
- 从浏览器将图像保存到手机多媒体资料中