photoGap 选择图片
从库中选择图片
在上一节中,我们学习了如何创建缩略图和"高质量"图像。在本节中,我们将学习如何使用 PhoneGap 从库中选择图片。从图库中选择图片的过程与使用相机拍照的过程相同。我们只需要添加一件事,即源类型。我们将在 takePic 函数中进行更改。
这些是用于从库中选择图片的以下步骤:
1 ) 创建一个新项目
首先,我们将使用一个空白模板创建一个新的 PhoneGap 项目。如果您不知道如何使用空白模板创建应用程序,请查看 PhoneGap 项目 链接。
2.创建 UI
现在,我们将使用 index.html 文件的主体部分并制作用于拍照并将其显示在显示器或屏幕上的 UI。此 UI 包含用于显示图片的按钮和图像区域。正文部分将被编码为:
<body>
<img id="imgArea" />
<button id="btnTakePicture"> Choose Picture </button>
<button id="btnClear"> Clear Picture </button>
<script type="text/javascript" src="cordova.js"></script>
</body>
3) 创建 window.onload 函数
现在,我们将创建 window.onload 函数。在此函数中,我们将获取两个按钮并将侦听器附加到它们。第一个按钮将调用 takepic 函数,第二个按钮调用匿名函数。在这个匿名函数中,我们将通过以下方式使用Id获取图像区域并将其源设置为null:
window.onload=function()
{
document.getElementById('btnTakePicture').addEventListener('click', takePic);
document.getElementById('btnClear').addEventListener('click',function(){
document.getElementById('imgArea').src="";
});
4) 创建 takePic 回调函数
现在,我们将创建 takePic 回调函数。在这个函数中,我们将设置我们之前讨论过的所有选项。我们将质量设置为 80,目标类型设置为文件 URI,源类型设置为照片库。我们将通过以下方式调用具有成功、失败、选项参数的导航器的 getPicture 函数:
function takePic(e)
{
var options = {
quality: 80,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
}
navigator.camera.getPicture(success, fail, options);
}
5) 创建成功和失败回调函数
失败回调函数只包含一个定义错误的警报消息。成功回调函数将图像作为参数。在这个函数中,我们将获取图像区域并在其中设置图像。
function success(thePicture)
{
var image = document.getElementById('imgArea');
image.src = thePicture;
}
function fail(e)
{
alert("Image failed: " + e.message);
}
现在,我们已准备好运行我们的项目。
完整代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<style>
#imgArea
{
border: 1px solid black;
max-width: 600px;
}
</style>
<script>
window.onload=function()
{
document.getElementById('btnTakePicture').addEventListener('click', takePic);
document.getElementById('btnClear').addEventListener('click',function(){
document.getElementById('imgArea').src="";
});
}
function takePic(e)
{
var options = {
quality: 80,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
}
navigator.camera.getPicture(success, fail, options);
}
function success(thePicture)
{
var image = document.getElementById('imgArea');
image.src = thePicture;
}
function fail(e)
{
alert("Image failed: " + e.message);
}
</script>
<title> Selecting Picture</title>
</head>
<body>
<img id="imgArea" />
<button id="btnTakePicture"> Choose Picture </button>
<button id="btnClear"> Clear Picture </button>
<script type="text/javascript" src="cordova.js"></script>
</body>
</html>
输出
