Android Open Source - gatoloco Snap Shot Activity






From Project

Back to project page gatoloco.

License

The source code is released under:

GNU General Public License

If you think the Android project gatoloco listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.grumpycat;
/*  ww w.  j  a v a  2 s.c  om*/
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;

public class SnapShotActivity extends Activity implements
    SurfaceHolder.Callback, Camera.PictureCallback {
  SurfaceView cameraView;
  SurfaceHolder surfaceHolder;
  Camera camera;
  Boolean currentCameraId = true;
  private int imageSelected = 1;
  final Context context = this;
  boolean loading = true;

  // final static String outputFilename = Environment
  // .getExternalStorageDirectory().getAbsolutePath() + "/madcat.jpg";

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Solo
                                      // vertical
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.activity_snapshot);

    /******************************** Configuracin de camara inicial *********************/
    cameraView = (SurfaceView) this.findViewById(R.id.CameraView);
    surfaceHolder = cameraView.getHolder();
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    surfaceHolder.addCallback(this);
    cameraView.setFocusable(true);
    cameraView.setFocusableInTouchMode(true);
    cameraView.setClickable(true);

    // camera.setDisplayOrientation(90);

    /******************************** Tomar foto ****************************************/
    ImageButton btnCapture = (ImageButton) findViewById(R.id.btnCapture);

    btnCapture.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        camera.takePicture(new ShutterCallback() {
          public void onShutter() {
            // final ProgressDialog pd = ProgressDialog.show(
            // context, "Processing", "Please wait", true,
            // false);
            //
            // new Thread(new Runnable() {
            // public void run() {
            // if (!loading)
            // pd.dismiss();
            // }
            // }).start();
          }
        }, new PictureCallback() {
          public void onPictureTaken(byte[] data, Camera camera) {
          }
        }, new PictureCallback() {
          public void onPictureTaken(byte[] data, Camera camera) {
            FileOutputStream outStream;
            try {

              // camera.setDisplayOrientation(90);
              // Leemos la foto principal
              Bitmap photo = BitmapFactory.decodeByteArray(data,
                  0, data.length);

              // Rotamos la imagen
              if (photo.getWidth() > photo.getHeight()) {
                Matrix matrix = new Matrix();
                matrix.postRotate(90);
                photo = Bitmap.createBitmap(photo, 0, 0,
                    photo.getWidth(), photo.getHeight(),
                    matrix, true);
              }
              // photo = photo.copy(photo.getConfig(), true);

              // Creamos la foto de superficie
              ImageView imgCenter = (ImageView) findViewById(R.id.imgCenter);
              int oHeight = imgCenter.getHeight();
              int oWidth = imgCenter.getWidth();
              Bitmap overlay = BitmapFactory.decodeResource(
                  getResources(),
                  getResources()
                      .getIdentifier(
                          "r"
                              + Integer
                                  .toString(imageSelected),
                          "drawable",
                          getPackageName()));
              // overlay = Bitmap.createScaledBitmap( overlay,
              // oWidth, oHeight, true );

              Canvas canvas = new Canvas(photo);
              // Calculamos la mitad de la foto
              int x = canvas.getWidth() / 2 - overlay.getHeight()
                  / 2;
              int y = canvas.getHeight() / 2 - overlay.getWidth()
                  / 2;

              canvas.drawBitmap(overlay, x, y, null);
              // Convinamos fotos
              try {
                FileOutputStream fos = new FileOutputStream(
                    Config.OUTPUT_FILENAME);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                photo.compress(CompressFormat.JPEG, 100, bos);
                byte[] bitmapdata = bos.toByteArray();
                fos.write(bitmapdata);
                fos.close();
              } catch (FileNotFoundException e) {
                Log.d(Config.LOG_NAME,
                    "File not found: " + e.getMessage());
                loading = false;
              } catch (IOException e) {
                Log.d(Config.LOG_NAME, e.toString());
                loading = false;
              }

            } finally {
              Intent intent = new Intent(SnapShotActivity.this,
                  SaveActivity.class);
              // camera.stopPreview();
              camera.release();
              // camera = null;
              loading = false;
              startActivity(intent);
            }

          }
        });
      }
    });

    /******************************** Rotacin de camaras ***********************************/
    ImageButton btnRotate = (ImageButton) findViewById(R.id.btnRotate);
    if (Camera.getNumberOfCameras() == 1) {
      btnRotate.setVisibility(View.INVISIBLE);
    }
    btnRotate.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        switchCamera();
      }
    });
    /******************************** Retornar a la pantalla anterior ************************/
    ImageButton btnBack = (ImageButton) findViewById(R.id.btnBack);
    btnBack.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        // camera.stopPreview();
        camera.release();
        // camera = null;
        onBackPressed();
      }
    });

    /******************************** Imagen Anterior ***************************************/
    ImageButton btnPrev = (ImageButton) findViewById(R.id.btnPrev);
    btnPrev.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        int prev = imageGo(-1);
        ImageView img = (ImageView) findViewById(R.id.imgCenter);
        img.setImageResource(getResources().getIdentifier(
            "r" + Integer.toString(prev), "drawable",
            getPackageName()));

      }
    });
    /******************************** Imagen Siguiente **************************************/
    ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext);
    btnNext.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        int next = imageGo(1);
        ImageView img = (ImageView) findViewById(R.id.imgCenter);
        img.setImageResource(getResources().getIdentifier(
            "r" + Integer.toString(next), "drawable",
            getPackageName()));
      }
    });
  }

  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // Camera.Parameters parameters = camera.getParameters();
    // parameters.setPreviewSize(w, h);
    // camera.setParameters(parameters);
    camera.startPreview();
  }

  public void surfaceCreated(SurfaceHolder holder) {
    camera = Camera.open();
    try {
      initDefaultCamera();
      camera.startPreview();
    } catch (IOException exception) {
      // camera.stopPreview();
      camera.release();
    }
  }

  public void surfaceDestroyed(SurfaceHolder holder) {
    // camera.stopPreview();
    camera.release();
    // camera = null;
  }

  // @Override
  public void onPictureTaken(byte[] data, Camera camera) {
    camera.startPreview();

  }

  // Botones de camara

  private int imageGo(int countGo) {
    imageSelected = imageSelected + countGo;
    if (imageSelected < 0)
      imageSelected = 10;
    else if (imageSelected > 10) {
      imageSelected = 1;
    }
    return imageSelected;
  }

  public void switchCamera() {
    int camNum = 0;//
    camNum = Camera.getNumberOfCameras(); // Nmero de camaras

    int camBackId = Camera.CameraInfo.CAMERA_FACING_BACK;
    int camFrontId = Camera.CameraInfo.CAMERA_FACING_FRONT;

    Camera.CameraInfo currentCamInfo = new Camera.CameraInfo();
    Log.i(Config.LOG_NAME, Integer.toString(currentCamInfo.facing));
    if (camera != null) {
      if (camNum > 1) {
        camera.release();
        if (!currentCameraId) {
          camera = Camera.open(camBackId);
          currentCameraId = true;
        } else {
          camera = Camera.open(camFrontId);
          currentCameraId = false;
        }
        try {

          // Aadido
          initDefaultCamera();
          camera.startPreview();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  public void initDefaultCamera() throws IOException {
    Camera.Parameters parameters = camera.getParameters();
    if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
      parameters.set("orientation", "portrait");
      camera.setDisplayOrientation(90);
    } else {
      parameters.set("orientation", "landscape");
      camera.setDisplayOrientation(0);
    }
    camera.setParameters(parameters);
    camera.setPreviewDisplay(surfaceHolder);
  }

  public Properties parsePropertiesString(String s) throws IOException {
    final Properties p = new Properties();
    p.load(new StringReader(s));
    return p;
  }

  public static void setCameraDisplayOrientation(Activity activity,
      int cameraId, android.hardware.Camera camera) {
    android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
    android.hardware.Camera.getCameraInfo(cameraId, info);
    int rotation = activity.getWindowManager().getDefaultDisplay()
        .getRotation();
    int degrees = 0;
    switch (rotation) {
    case Surface.ROTATION_0:
      degrees = 0;
      break;
    case Surface.ROTATION_90:
      degrees = 90;
      break;
    case Surface.ROTATION_180:
      degrees = 180;
      break;
    case Surface.ROTATION_270:
      degrees = 270;
      break;
    }

    int result;
    if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
      result = (info.orientation + degrees) % 360;
      result = (360 - result) % 360; // compensate the mirror
    } else { // back-facing
      result = (info.orientation - degrees + 360) % 360;
    }
    camera.setDisplayOrientation(result);
  }

  // Funciones adicionales
  private DisplayMetrics getDisplayMetrics() {
    Display localDisplay = getWindow().getWindowManager()
        .getDefaultDisplay();
    DisplayMetrics localDisplayMetrics = new DisplayMetrics();
    localDisplay.getMetrics(localDisplayMetrics);
    return localDisplayMetrics;
  }
}




Java Source Code List

com.grumpycat.Config.java
com.grumpycat.GalleryActivity.java
com.grumpycat.MainActivity.java
com.grumpycat.Preview.java
com.grumpycat.SaveActivity.java
com.grumpycat.SnapShotActivity.java
com.grumpycat.SplashActivity.java
com.grumpycat.utils.FileUtils.java