Working with Camera in Android

//
//Taking a photo using camera, save in default camera location and show in ImageView 
control-
//

<uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

public void TakePhoto(View view)
{
    Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(imageIntent, REQUEST_IMAGE_CAPTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK)
    {
        Bundle bundle = data.getExtras();
        Bitmap bitmap = (Bitmap) bundle.get("data");

        ImageView imageView=(ImageView)findViewById(R.id.ivPhoto);
        imageView.setImageBitmap(bitmap);
    }
}

//
//Display photo from default Camera directory with a given name in an ImageView 
//

//Modify manifest file
<uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

//Modify build.gradle(Module:app) as follows-
compile 'com.squareup.picasso:picasso:2.5.2'

public void ShowPhoto(View view)
{
    EditText PhotoNameTextbox=(EditText)findViewById(R.id.txtPhotoName);
    String PhotoName= PhotoNameTextbox.getText().toString() + ".jpg";

    //Get default camera directory
    File CameraDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString(), "Camera"); // DIRECTORY_PICTURES

    //Photo path
    File photoFile= new File(CameraDirectory + File.separator + PhotoName);

    if (photoFile.exists())
    {
        ImageView imageView=(ImageView)findViewById(R.id.ivPhoto);

       //Following lines can be another option to show photo. Currently not required.
       /*Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
        imageView.setImageBitmap(bitmap);*/

       //Picasso is a third party library. http://square.github.io/picasso/
       Picasso.with(getApplicationContext()).load(photoFile).fit()
              .centerCrop().into(imageView);

    }
    else
    {
       Toast.makeText(DisplayPhoto.this, "Photo not found", Toast.LENGTH_SHORT).show();
     }
}

//
//Take a photo, Save with custom name, then display in ImageView
//

//Modify manifest file
<uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

//Modify build.gradle(Module:app) as follows-
compile 'com.squareup.picasso:picasso:2.5.2'

public class TakePhotoAndSaveWithCustomNameAndPath extends AppCompatActivity
{
    File CameraDirectory;
    String photoName;
    static final int REQUEST_IMAGE_CAPTURE = 101;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_photo_and_save_with_custom_name_and_path);
        CameraDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString(), "Camera");
    }
    
    public void TakePhoto(View view){
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        
        photoName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        Log.d("CustomPhotoName",photoName);
        File photo = new File(CameraDirectory, photoName + ".jpg");
        Uri uriSavedImage = Uri.fromFile(photo);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

            try{
                ImageView imageView=(ImageView)findViewById(R.id.imageviewImage);
                File photo = new File(CameraDirectory, photoName + ".jpg");
                if(photo.exists()){
                    //Picasso is a third party library. http://square.github.io/picasso/
                    Picasso.with(getApplicationContext()).load(photo).fit().centerCrop().into(imageView);
                }
                else{
                    Log.d("PhotoFileStatus","Not found");
                }
            }
            catch (Exception ex){
                Log.d("PhotoError",ex.getMessage().toString());
                Toast.makeText(TakePhotoAndSaveWithCustomNameAndPath.this, ex.getMessage().toString(), Toast.LENGTH_LONG).show();
            }

        }
    }
}
Advertisements

Android- Capture & Display Photo

MainActivity.java

package com.imslbd.firstcameraapp;

import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView txtChangeName;
    ImageView mImageView;
    static final int REQUEST_IMAGE_CAPTURE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       txtChangeName =(TextView) findViewById(R.id.txtDisplayName);
        mImageView=(ImageView) findViewById(R.id.imageView);
    }

    public  void ChangeName(View view)
    {
        dispatchTakePictureIntent();
        txtChangeName.setText("Hello");
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            mImageView.setImageBitmap(imageBitmap);
        }
    }
}

actiivity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.imslbd.firstcameraapp.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/txtDisplayName" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/btnButton"
        android:layout_below="@+id/txtDisplayName"
        android:layout_alignParentStart="true"
        android:onClick="ChangeName" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/btnButton"
        android:layout_marginTop="41dp">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageView"
            android:layout_gravity="center_vertical" />
    </LinearLayout>

</RelativeLayout>


-------------------------------------------------------

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.imslbd.firstcameraapp">

    <uses-feature android:name="android.hardware.camera"  android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Upload multiple files using AJAX- ASP.NET MVC (multiple file input with same class)

This technique is used to upload multiple files/photos by using multiple file input control (dynamically added), AJAX and ASP.NET-

1. Multiple file input control (with same .class)
2. JQuery AJAX
3. Form collection for additional data
4. ASP.NET MVC

HTML Part
----------------------------------------

<div class="form-group">
    <input class="multiplephoto" type="file" name="files" multiple />
</div>

<button id="AddMorePhoto">Add more photo </button>
Adding another file input
-----------------------------------------

 $('#AddMorePhoto').on('click', function (e) {
         e.preventDefault();
         $('<div/>').addClass('form-group')
         .html($('<input class="button multiplephoto" type="file" name="files" multiple />'))
         .insertBefore(this);

 });


Submitting the form as FormData via AJAX
-----------------------------------------

var fd = new FormData();

//append some other data to fd. i.e.-
fd.append('PersonName', personName);

var inputs = $('.multiplephoto');
$.each(inputs, function (obj, v) {
    var file = v.files[0];
    fd.append("photos", file);
    //var filename = $(v).attr("data-filename");
});

$.ajax({
    url: "/ControllerName/ActionMethodName",
    type: "POST",
    data: fd,
    processData: false,  // tell jQuery not to process the data
    contentType: false,   // tell jQuery not to set contentType
    beforeSend: function () {
    },
    success: function (response) {
    },
    error: function (request, status, error) {
    },
    complete: function () {
    }

});
Server-side code
------------------------------------

[HttpPost]
public JsonResult GetPhotos(IEnumerable<HttpPostedFileBase> photos, FormCollection data)
{
    var directory = HttpContext.Server.MapPath("~/Photos");
                
    foreach (var file in photos)
    {
        String fileName = file.FileName;
        string imagePath = Path.Combine(directory, "LoginPhotos", fileName);
        file.SaveAs(imagePath);
    }

    return Json("success");

}

Upload multiple files ASP.NET MVC without AJAX

<form enctype="multipart/form-data" action="/SubmitImage"
         method="post" >
    <input type="file" name="photos" multiple />
    <input type="text" name="caption"/>
    <textarea name="description"></textarea>
    <input type="submit" value="Submit" />
</form>
[ValidateInput(false)]
[HttpPost]
public ActionResult SubmitImage(IEnumerable<HttpPostedFileBase> photos,
                                   FormCollection data)
{
    String authString = Request.QueryString["auth"].ToString();
 
    String caption = data["caption"].ToString();
    string description = data["description"].ToString();
 
    if (Request.Files["photos"] != null)
    {
        //The directory where photo will be saved.
        var directory = HttpContext.Server.MapPath("~/Photos");
        foreach (var photo in photos)
        {
            //Get the file name of photo as it being sent.
            //It's required to get the original file extension.
            var photoName = photo.FileName.ToString();
            var extension = Path.GetExtension(photoName).ToLower();
            //Give photo a new name so that it can avoid duplicate name.
            var newName = Guid.NewGuid() + extension;
            string filePath = Path.Combine(directory, newName);
 
            //Check file existence. If exist, try another name.
            if (System.IO.File.Exists(filePath))
            {
               newName = Guid.NewGuid() + extension;
            }
             
            string filePath = Path.Combine(directory, newName);
            photo.SaveAs(filePath); //saving the photo to directory.                    
        }
    }
 
    return RedirectToAction("Index", "UploadImage", new { auth = authString, issubmitted = true });
}

Upload multiple files using AJAX- ASP.NET MVC

This technique is used to upload multiple files/photos by using single file input control, AJAX and ASP.NET-

1. Single file input control
2. JQuery AJAX
3. Form collection for additional data
4. ASP.NET MVC

<input type="file" id="Photos" multiple />
<!--Save button is disabled to prevent empty file submission-->
<button id="SavePhotos" disabled>Save</button>
<script>
$(function () {
    var fd, saveButton = $("#SavePhotos");
    $("#Photos").change(function (e) {
        fd = new FormData();
        fd.append("id", 1);    
        $.each(e.target.files, function (index, file) {
            fd.append("photos", file);
        });
        saveButton.prop("disabled", false)
    });

    saveButton.click(function () {
        $.ajax({
            url: URL-To-Submit,
            type: 'POST',
            data: fd,
            processData: false,
            contentType: false,
            beforeSend: function () {
            },
            success: function (response) {
                console.log(response);
            },
            error: function (request, status, error) {
            },
            complete: function () {
            }
        });
    });
});
[HttpPost]
public JsonResult SavePhotos(IEnumerable<HttpPostedFileBase> photos, FormCollection data)
{
    try
    {
        var directory = HttpContext.Server.MapPath("~/Photos");

        foreach (var file in photos)
        {
            String fileName = file.FileName;
            String fileExtension = Path.GetExtension(fileName);

            string imagePath = Path.Combine(directory, "HubPhotos", fileName);
            file.SaveAs(imagePath);
        }
    }
    catch (Exception Ex)
    {
        LogException(Ex);
    }

    return Json("success");
}