【问题标题】:Capture a photo by invoking Camera and save it to the SD card or sql database in worklight通过调用Camera 拍摄照片并将其保存到SD 卡或worklight 中的sql 数据库中
【发布时间】:2016-04-11 16:25:35
【问题描述】:

我看到了有关使用本机相机和为我们自己的应用程序拍摄照片的各种链接。但是我很难将照片保存到设备或存储在数据库中。我有包含文件路径等的代码。但我不知道在程序中的何处包含这些代码。请帮帮我。

我已使用以下 URL 实现相机 http://docs.phonegap.com/en/2.0.0/cordova_camera_camera.md.html

我正在使用 worklight 和 apache cordova 来调用相机。

File sdDir = Environment.getExternalStorageDirectory();

在脚本中的何处包含上述行?

如何以及在何处将 img 标签包含在 HTML 中?

如何将图片转成base64并存入数据库?


我附上了下面的代码。请交叉检查我使用的功能并帮助我。

<!DOCTYPE html>
<html>
  <head>
 <title>Capture Photo</title>

<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8">

var pictureSource;   // picture source
var destinationType; // sets the format of returned value 

// Wait for PhoneGap to connect with the device
//
document.addEventListener("deviceready",onDeviceReady,false);

// PhoneGap is ready to be used!
//
function onDeviceReady() {
    pictureSource=navigator.camera.PictureSourceType;
    destinationType=navigator.camera.DestinationType;
}

// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
  // Uncomment to view the base64 encoded image data
  // console.log(imageData);

  // Get image handle
  //
  var smallImage = document.getElementById('smallImage');

  // Unhide image elements
  //
  smallImage.style.display = 'block';

  // Show the captured photo
  // The inline CSS rules are used to resize the image
  //
  smallImage.src = "data:image/jpeg;base64," + imageData;
}

// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
  // Uncomment to view the image file URI 
  // console.log(imageURI);

  // Get image handle
  //
  var largeImage = document.getElementById('largeImage');

  // Unhide image elements
  //
  largeImage.style.display = 'block';

  // Show the captured photo
  // The inline CSS rules are used to resize the image
  //
  largeImage.src = imageURI;
}

// A button will call this function
//
function capturePhoto() {

String fileName = System.currentTimeMillis()+".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
fileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);



  // Take picture using device camera and retrieve image as base64-encoded string
 navigator.camera.getPicture(onSuccess, onFail, { quality: 50 }); 

function onSuccess(imageData) {
    var image = document.getElementById('myImage');
    image.src = "data:image/jpeg;base64," + imageData;
}

function onFail(message) {
    alert('Failed because: ' + message);
}
}

// A button will call this function
//


// Called if something bad happens.
// 
function onFail(message) {
  alert('Failed because: ' + message);
}

    </script>
  </head>
  <body>
    <button onclick="capturePhoto();">Capture Photo</button> <br>

    <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
    <img style="display:none;" id="largeImage" src="" />
  </body>
</html>

【问题讨论】:

  • 这需要一个详尽的答案,您是否正确使用了链接中所述的 navaigator.camera.getpicture() ?你能拍张照片吗!如果是,请在提供的问题中分享您的代码。我是否正确假设您想获取捕获的图像的 uri?您想要手机中图像的位置,并且您想在屏幕上显示您的图像和/或将其保存到数据库中?现在你必须 imaplement websql/sqlite 存储插入操作。使用代码示例恢复并编辑您的问题
  • @IamKarim1992 请在下面找到代码并提供帮助。
  • @IamKarim1992 你说得对,我想在 HTML 中显示图像并存储在在线数据或 mysql 中。如果捕获的图片在新页面中,那就更好了。
  • 先把你的代码拿来拍照,可以找到很多关于如何使用 navigator.camera.getpicture(onSuccess,onError,options) 的例子,然后从那里开始工作。跨度>
  • 我可以拍照,但不能像我之前提到的那样显示或说出来。 @IamKarim1992

标签: android cordova ibm-mobilefirst


【解决方案1】:

我也在努力解决同样的问题,并通过在启动相机活动之前定义图像 uri 找到了解决方案,如下所示:

当你想启动相机时,点击下面的方法。

private void getImages() {
    String fileName = System.currentTimeMillis()+".jpg";
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, fileName);
    fileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

我已将图像名称作为当前时间戳记,这样每次图像都会有一个新名称,并且不会有冗余。也无需将图像更改为 base64 简单更改为位图并显示到您的图像视图,如果要将图像视图存储到数据库然后将 uri 保存为字符串数据类型在上面的代码行变量 fileuri 是字符串类型,如果你想将图像存储在您的 sqlte 中,然后保存该 fileuri。

由于您已经定义了图像 uri,因此无需从 onActivityResult 获取 uri,并且图像将自动保存在您的手机中,而无需调用 onActivityResult。

仅要获得预览或将图像显示到您的图像视图,您必须调用 onActivityResult()。

要在 yourimageView 中显示图像,请编写以下代码。

@Override
public void onActivityResult(int requestCode, int resultCode, final Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == HomeActivity.RESULT_OK) {
            try{
            BitmapFactory.Options options = new BitmapFactory.Options();
            // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8; 
        final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                options);

        yourimgView.setImageBitmap(bitmap);
            }catch (NullPointerException e) {
        e.printStackTrace();
    }
            }
        } else if (resultCode == HomeActivity.RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(this,
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Toast.makeText(this,
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }

}

【讨论】:

  • 谢谢@HAXM,您为 yourimageView 提供的编码是用 Java 编写的。能不能用脚本语言JS说一下?
  • 对不起哥们我只知道java:(
  • 找到上面的代码并尽可能地帮助我@HAXM
  • 好吧,如果您只使用 capturePhoto() 和 onSucess() 这两种方法,我检查了您的代码并发现一切都是正确的,但是由于我对脚本语言很天真,我不能说您应该使用其他功能与否。
  • 谢谢@HAXM :)
【解决方案2】:

我已经使用 cordova 的 File API 插件实现了这一点,

这里是链接https://github.com/wymsee/cordova-imagePicker

<!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html>
    <head>
        <!--
        Customize this policy to fit your own app's needs. For more guidance, see:
            https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy
        Some notes:
            * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
            * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
            * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
                * Enable inline JS: add 'unsafe-inline' to default-src
        -->

        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>Hello World</title>
    </head>
    <body>
        <div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
                <button style="width:30%;" onclick="pickImage()">Clean Data</button>
                <p id="lastPhoto"></p>
            </div>
        </div>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
         <script type="text/javascript" src="js/jquery.min.js"></script>
        <script type="text/javascript">
            function pickImage(){
                var lastPhotoContainer = document.getElementById("lastPhoto");
                var doc= document.getElementBy
                window.imagePicker.getPictures(
                function(results) {
                    console.log(results);
                        for (var i = 0; i < results.length; i++) {
                        var imageUri=results[i];
                        console.log('Image URI: ' + results[i]);
                        lastPhotoContainer.innerHTML = "<img src='" + imageUri + "' style='width: 75%;' />";
                        }
                    }, function (error) {
                        console.log('Error: ' + error);
                }
            );
            }
        </script>
    </body>
</html>

这个简单的示例从本地存储中获取单个图像并将其显示在应用程序的屏幕上,您可以继续将图像从 uri 转换为 base64 并按照您的喜好使用它。现在 thsi 将填充已经将图片转换为 html ..希望这会有所帮助。

【讨论】:

  • 我会处理这个并返回给你@IamKarim1992
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多