I have to draw the circle in center of the captured image in image view and saved in DB. First capture the image and crop the image and draw circle in center of the image and display in image view and saved in DB. circle is not drawnn. I tried so many methodologies. please help me.
activity_main.xml
<LinearLayout 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:gravity="center_horizontal"
android:orientation="vertical"
android:baselineAligned="false"
tools:context=".MainActivity"
android:weightSum="1">
<Button
android:id="#+id/btn_select_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:text="Select Image" />
<LinearLayout
android:layout_width="226dp"
android:layout_height="231dp"
android:orientation="vertical"
android:weightSum="1">
<ImageView
android:id="#+id/img_photo"
android:layout_width="200dp"
android:layout_height="500dp"
android:layout_marginTop="10dp"
android:scaleType="fitXY"
android:layout_weight="0.45" />
</LinearLayout>
<LinearLayout
android:layout_width="280dp"
android:layout_height="77dp"
android:gravity="center_vertical|center_horizontal"
android:orientation="horizontal">
<TextView
android:id="#+id/xPos"
android:layout_width="5dp"
android:layout_height="wrap_content"
android:layout_weight="0.32"
android:gravity="left|center_vertical"
android:padding="5dip"
android:visibility="invisible" />
<TextView
android:id="#+id/yPos"
android:layout_width="5dp"
android:layout_height="wrap_content"
android:layout_weight="0.32"
android:gravity="right|center_vertical"
android:padding="5dip"
android:visibility="invisible" />
</LinearLayout>
</LinearLayout>
MainActivity.java
package knuckle.app.com.knuckleauthentication;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import knuckle.app.com.knuckleauthentication.R;
import static android.R.attr.bitmap;
import static android.R.attr.color;
import static android.R.attr.path;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import android.content.Context;
import android.view.ViewGroup.LayoutParams;
public class MainActivity extends AppCompatActivity {
private final static int REQUEST_PERMISSION_REQ_CODE = 34;
private static final int CAMERA_CODE = 101, GALLERY_CODE = 201, CROPING_CODE = 301;
public static final int MEDIA_TYPE_IMAGE = 1;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Knuckle Images";
private Button btn_select_image;
private TextView txt_x_pos, txt_y_pos;
private ImageView imageView;
private Uri mImageCaptureUri;
private File outPutFile = null;
private DataHelper dbHelper;
FrameLayout preview = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper=new DataHelper(this);
outPutFile = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
txt_x_pos = (TextView) findViewById(R.id.xPos);
txt_y_pos = (TextView) findViewById(R.id.yPos);
btn_select_image = (Button) findViewById(R.id.btn_select_image);
imageView = (ImageView) findViewById(R.id.img_photo);
btn_select_image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImageOption();
}
});
}
private void selectImageOption() {
final CharSequence[] items = { "Capture Photo", "Choose from Gallery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Capture Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
mImageCaptureUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
startActivityForResult(intent, CAMERA_CODE);
} else if (items[item].equals("Choose from Gallery")) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, GALLERY_CODE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onResume() {
super.onResume();
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_REQ_CODE);
return;
}
}
#Override
public void onRequestPermissionsResult(final int requestCode, final #NonNull String[] permissions, final #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_PERMISSION_REQ_CODE: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission denied.", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK && null != data) {
mImageCaptureUri = data.getData();
System.out.println("Gallery Image URI : "+mImageCaptureUri);
CropingIMG();
} else if (requestCode == CAMERA_CODE && resultCode == Activity.RESULT_OK) {
System.out.println("Camera Image URI : "+mImageCaptureUri);
CropingIMG();
} else if (requestCode == CROPING_CODE) {
try {
if(outPutFile.exists()){
Bitmap photo = decodeFile(outPutFile);
imageView.setImageBitmap(photo);
/* BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inDither = true;
bfo.inScaled = false;
bfo.inPreferredConfig = Bitmap.Config.ARGB_8888;
bfo.inPurgeable = true;
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.id.img_photo, bfo);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(10);
paint.setColor(Color.RED);
Bitmap workingBitmap = Bitmap.createBitmap(bm);
Bitmap mutuableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutuableBitmap);
canvas.drawCircle(60, 50, 15, paint);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(mutuableBitmap);*/
//
// preview.addView(imageView);
// Display display = getWindowManager().getDefaultDisplay();
//Point size = new Point(photo.getHeight()/2, photo.getWidth()/2);
//display.getSize(size);
// int screenCenterX = (size.x/2);
//int screenCenterY = (size.y/2) ;
//DrawOnTop mDraw = new DrawOnTop(this,screenCenterX,screenCenterY);
//addContentView(mDraw, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
// txt_x_pos.setText(screenCenterX);
// txt_y_pos.setText(screenCenterY);
createBitMap();
dbHelper.insertBitmap(photo);
Toast.makeText(getApplicationContext(),
"Knuckle Image Saved successfully.",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Error while save image", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void createBitMap() {
Bitmap bitMap = BitmapFactory.decodeResource(null, R.id.img_photo); //creates bmp
bitMap = bitMap.copy(bitMap.getConfig(), true); //lets bmp to be mutable
Canvas canvas = new Canvas(bitMap); //draw a canvas in defined bmp
Paint paint = new Paint(); //define paint and paint color
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(15);
paint.setAntiAlias(true); //smooth edges
Display display = getWindowManager().getDefaultDisplay();
int centerX = display.getWidth()/2;
int centerY = display.getHeight()/2;
float canvasX = (float) canvas.getWidth();
float canvasY = (float) canvas.getHeight();
float bitmapX = (float) bitMap.getWidth();
float bitmapY = (float) bitMap.getHeight();
float boardPosX = ((canvasX/2) - (bitmapX/2));
float boardPosY = ((canvasY /2)- (bitmapY/2));
canvas.drawBitmap(bitMap, boardPosX, boardPosY, paint);
canvas.drawCircle(centerX, centerY, 3, paint);
imageView.setImageBitmap(bitMap);
}
private void CropingIMG() {
final ArrayList<CropingOption> cropOptions = new ArrayList<CropingOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Cann't find image croping app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 512);
intent.putExtra("outputY", 512);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
//TODO: don't use return-data tag because it's not return large image data and crash not given any message
//intent.putExtra("return-data", true);
//Create output file here
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outPutFile));
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = (ResolveInfo) list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROPING_CODE);
} else {
for (ResolveInfo res : list) {
final CropingOption co = new CropingOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropingOptionAdapter adapter = new CropingOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Croping App");
builder.setCancelable(false);
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROPING_CODE);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 512;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
}
class DrawOnTop extends View {
int screenCenterX = 0;
int screenCenterY = 0;
final int radius = 15;
public DrawOnTop(Context context, int screenCenterX, int screenCenterY) {
super(context);
this.screenCenterX = screenCenterX;
this.screenCenterY = screenCenterY;
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
Paint p = new Paint();
p.setColor(Color.RED);
DashPathEffect dashPath = new DashPathEffect(new float[]{5,5}, (float)1.0);
p.setPathEffect(dashPath);
p.setStyle(Paint.Style.STROKE);
canvas.drawCircle(screenCenterX, screenCenterY, radius, p);
invalidate();
super.onDraw(canvas);
}
}
CroppingOption.java
package knuckle.app.com.knuckleauthentication;
import android.content.Intent;
import android.graphics.drawable.Drawable;
/**
* Created by DP on 7/12/2016.
*/
public class CropingOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
CroppingOptionAdapter.java
package knuckle.app.com.knuckleauthentication;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import knuckle.app.com.knuckleauthentication.R;
import android.support.v7.app.AppCompatActivity;
public class CropingOptionAdapter extends ArrayAdapter {
private ArrayList mOptions;
private LayoutInflater mInflater;
public CropingOptionAdapter(Context context, ArrayList options) {
super(context, R.layout.croping_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.croping_selector, null);
CropingOption item = (CropingOption) mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.img_icon)).setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.txt_name)).setText(item.title);
return convertView;
}
return null;
}
}
Datahelper.java
package knuckle.app.com.knuckleauthentication;
import java.io.ByteArrayOutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
public class DataHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "knuckledb";
public static final String TABLE_NAME = "tbl_knuckle_img";
public static final int DATABASE_VERSION = 1;
public static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT, img BLOB NOT NULL, description TEXT NULL)";
public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
public DataHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
// Create the table
db.execSQL(CREATE_TABLE);
}
//Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop older table if existed
db.execSQL(DELETE_TABLE);
//Create tables again
onCreate(db);
}
public void insertBitmap(Bitmap bm) {
// Convert the image into byte array
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
byte[] buffer = out.toByteArray();
// Open the database for writing
SQLiteDatabase db = this.getWritableDatabase();
// Start the transaction.
db.beginTransaction();
ContentValues values;
int width=bm.getWidth();
int height=bm.getHeight();
int centerX=width/2;
int centerY=height/2;
try {
values = new ContentValues();
values.put("img", buffer);
values.put("description", "knuckle image");
values.put("centerX", centerX);
values.put("centerY", centerY);
// Insert Row
long i = db.insert(TABLE_NAME, null, values);
Log.i("Insert", i + "");
// Insert into database successfully.
db.setTransactionSuccessful();
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
db.endTransaction();
// End the transaction.
db.close();
// Close database
}
}
public Bitmap getBitmap(int id) {
Bitmap bitmap = null;
// Open the database for reading
SQLiteDatabase db = this.getReadableDatabase();
// Start the transaction.
db.beginTransaction();
try {
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE id = " + id;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
// Convert blob data to byte array
byte[] blob = cursor.getBlob(cursor.getColumnIndex("img"));
// Convert the byte array to Bitmap
bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length);
}
}
db.setTransactionSuccessful();
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
db.endTransaction();
// End the transaction.
db.close();
// Close database
}
return bitmap;
}
}
you want draw image like in this link
[draw circle image] https://github.com/youssefshaaban/Show-Round-Image-from-Webservice
you can use file RoundedImageView.java in your app and use it in XMl Layout instead of ImageView
Related
Context:
I used a template of an android app from https://github.com/pramod722445/Custom_Object_Detection_App
and added java files to detect images from a video. I trained the model on Google Colab and converted it to a tflite file and renamed it as bline_model.tflite with a text folder with the label bline_label.txt in Android Studio. When I run the application, it stops/crashes after the video to image phase is done. I think the error originates from either objectDetectorClass.java or PreviewImageActivity.java. How do I fix it?
CODE
MainActivity.java
package bline.detector.com.ffmpegvideoeditor.activity;
import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.github.hiteshsondhi88.libffmpeg.ExecuteBinaryResponseHandler;
import com.github.hiteshsondhi88.libffmpeg.FFmpeg;
import com.github.hiteshsondhi88.libffmpeg.LoadBinaryResponseHandler;
import com.github.hiteshsondhi88.libffmpeg.exceptions.FFmpegCommandAlreadyRunningException;
import com.github.hiteshsondhi88.libffmpeg.exceptions.FFmpegNotSupportedException;
import org.florescu.android.rangeseekbar.RangeSeekBar;
import org.opencv.android.OpenCVLoader;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import bline.detector.com.ffmpegvideoeditor.R;
public class MainActivity extends AppCompatActivity {
static {
if (!OpenCVLoader.initDebug())
Log.d("ERROR", "Unable to load OpenCV");
else
Log.d("SUCCESS", "OpenCV loaded");
}
private Button uploadVideo;
private Button extractImages;
private VideoView videoView;
private String filePath;
private static final String FILEPATH = "filepath";
private Uri selectedVideoUri;
private FFmpeg ffmpeg;
private static final int REQUEST_TAKE_GALLERY_VIDEO = 100;
private static final String TAG = "amirah";
private int choice = 0;
private ProgressDialog progressDialog;
private RangeSeekBar rangeSeekBar;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
uploadVideo = (Button) findViewById(R.id.uploadVideo);
extractImages = (Button) findViewById(R.id.extractImages);
videoView = (VideoView) findViewById(R.id.videoView);
rangeSeekBar = (RangeSeekBar) findViewById(R.id.rangeSeekBar);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(null);
progressDialog.setCancelable(false);
rangeSeekBar.setEnabled(false);
loadFFMpegBinary();
uploadVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= 23)
getPermission();
else
uploadVideo();
}
});
extractImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
choice = 1;
if (selectedVideoUri != null) {
extractImagesVideo(rangeSeekBar.getSelectedMinValue().intValue() * 1000, rangeSeekBar.getSelectedMaxValue().intValue() * 1000);
} else
Toast.makeText(MainActivity.this, "Please Upload a Video", Toast.LENGTH_LONG).show();
}
});
}
private void getPermission() {
String[] params = null;
String writeExternalStorage = Manifest.permission.WRITE_EXTERNAL_STORAGE;
String readExternalStorage = Manifest.permission.READ_EXTERNAL_STORAGE;
int hasWriteExternalStoragePermission = ActivityCompat.checkSelfPermission(this, writeExternalStorage);
int hasReadExternalStoragePermission = ActivityCompat.checkSelfPermission(this, readExternalStorage);
List<String> permissions = new ArrayList<String>();
if (hasWriteExternalStoragePermission != PackageManager.PERMISSION_GRANTED)
permissions.add(writeExternalStorage);
if (hasReadExternalStoragePermission != PackageManager.PERMISSION_GRANTED)
permissions.add(readExternalStorage);
if (!permissions.isEmpty()) {
params = permissions.toArray(new String[permissions.size()]);
}
if (params != null && params.length > 0) {
ActivityCompat.requestPermissions(MainActivity.this,
params,
100);
} else
uploadVideo();
}
/**
* Handling response for permission request
*/
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 100: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
uploadVideo();
}
}
break;
}
}
private void uploadVideo() {
try {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video"), REQUEST_TAKE_GALLERY_VIDEO);
} catch (Exception e) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
selectedVideoUri = data.getData();
videoView.setVideoURI(selectedVideoUri);
videoView.start();
}
}
}
private void loadFFMpegBinary() {
try {
if (ffmpeg == null) {
ffmpeg = FFmpeg.getInstance(this);
}
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
#Override
public void onFailure() { showUnsupportedExceptionDialog();
}
#Override
public void onSuccess() {
Log.d(TAG, "ffmpeg: successfully Loaded");
}
});
} catch (FFmpegNotSupportedException e) {
showUnsupportedExceptionDialog();
} catch (Exception e) {
Log.d(TAG, "exception: " + e);
}
}
private void showUnsupportedExceptionDialog() {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Not Supported")
.setMessage("Device Not Supported")
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.finish();
}
})
.create()
.show();
}
private void extractImagesVideo(int startMs, int endMs) {
File moviesDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
);
String filePrefix = "extract_picture";
String fileExtn = ".jpg";
String yourRealPath = getPath(MainActivity.this, selectedVideoUri);
File dir = new File(moviesDir, "VideoEditor");
int fileNo = 0;
while (dir.exists()) {
fileNo++;
dir = new File(moviesDir, "VideoEditor" + fileNo);
}
dir.mkdir();
filePath = dir.getAbsolutePath();
File dest = new File(dir, filePrefix + "%03d" + fileExtn);
Log.d(TAG, "startTrim: src: " + yourRealPath);
Log.d(TAG, "startTrim: dest: " + dest.getAbsolutePath());
String[] complexCommand = {"-y", "-i", yourRealPath, "-an", "-r", "1", "-ss", "" + startMs / 1000, "-t", "" + (endMs - startMs) / 1000, dest.getAbsolutePath()};
execFFmpegBinary(complexCommand);
}
//-y overwrite output files without asking
//-i ffmpeg reads from an arbitrary number of input "files" specified by the -i option
//-an disable audio recordings
//-r 1/2 will extract one image frame from every 2 second of video
//-r 1/2 will extract one image frame from every 2 second of video.Similarly, -r 1 will extract one image frame from every second of the video.
//remove -r option if u want to extract all video frames as images from the specified time duration
//-ss seeks to position
//-t limit the duration of data read from the input file
private void execFFmpegBinary(final String[] command) {
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
#Override
public void onFailure(String message) {
Log.d(TAG, "FAILED with output: " + message);
}
#Override
public void onSuccess(String s) {
Log.d(TAG, "SUCCESS with output: " + s);
Intent intent = new Intent(MainActivity.this, PreviewImageActivity.class);
intent.putExtra(FILEPATH, filePath);
startActivity(intent);
}
#Override
public void onProgress(String s) {
Log.d(TAG, "Started command : ffmpeg " + command);
if (choice == 1)
progressDialog.setMessage("progress: " + s);
Log.d(TAG, "progress : " + s);
}
#Override
public void onStart() {
Log.d(TAG, "Started command : ffmpeg " + command);
progressDialog.setMessage("Processing...");
progressDialog.show();
}
#Override
public void onFinish() {
Log.d(TAG, "Finished command : ffmpeg " + command);
if (choice == 1) {
progressDialog.dismiss();
}
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// do nothing for now
}
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
if (children != null) {
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
}
return dir.delete();
}
private String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri.
*/
private String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
private boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
}
objectDetectorClass.java
package bline.detector.com.ffmpegvideoeditor.activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import org.tensorflow.lite.Interpreter;
import org.tensorflow.lite.gpu.GpuDelegate;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class objectDetectorClass {
// used to load model and predict
private Interpreter interpreter;
// store all label in array
private List<String> labelList;
private int INPUT_SIZE;
private int PIXEL_SIZE=3; // for RGB
private int IMAGE_MEAN=0;
private float IMAGE_STD=255.0f;
// use to initialize gpu in app
private GpuDelegate gpuDelegate;
private int height=0;
private int width=0;
objectDetectorClass(AssetManager assetManager,String modelPath, String labelPath,int inputSize) throws IOException{
INPUT_SIZE=inputSize;
// use to define gpu or cpu // no. of threads
Interpreter.Options options=new Interpreter.Options();
gpuDelegate=new GpuDelegate();
options.addDelegate(gpuDelegate);
options.setNumThreads(4); // set it according to your phone
// loading model
interpreter=new Interpreter(loadModelFile(assetManager,modelPath),options);
// load labelmap
labelList=loadLabelList(assetManager,labelPath);
}
private List<String> loadLabelList(AssetManager assetManager, String labelPath) throws IOException {
// to store label
List<String> labelList=new ArrayList<>();
// create a new reader
BufferedReader reader=new BufferedReader(new InputStreamReader(assetManager.open(labelPath)));
String line;
// loop through each line and store it to labelList
while ((line=reader.readLine())!=null){
labelList.add(line);
}
reader.close();
return labelList;
}
private ByteBuffer loadModelFile(AssetManager assetManager, String modelPath) throws IOException {
// use to get description of file
AssetFileDescriptor fileDescriptor=assetManager.openFd(modelPath);
FileInputStream inputStream=new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel=inputStream.getChannel();
long startOffset =fileDescriptor.getStartOffset();
long declaredLength=fileDescriptor.getDeclaredLength();
return fileChannel.map(FileChannel.MapMode.READ_ONLY,startOffset,declaredLength);
}
public Mat recognizeVideo(Mat mat_image){
Bitmap bitmap=null;
bitmap=Bitmap.createBitmap(mat_image.cols(),mat_image.rows(),Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mat_image,bitmap);
height=bitmap.getHeight();
width=bitmap.getWidth();
// scale the bitmap to input size of model
Bitmap scaledBitmap=Bitmap.createScaledBitmap(bitmap,INPUT_SIZE,INPUT_SIZE,false);
// convert bitmap to bytebuffer as model input should be in it
ByteBuffer byteBuffer=convertBitmapToByteBuffer(scaledBitmap);
// defining output
Object[] input=new Object[1];
input[0]=byteBuffer;
Map<Integer,Object> output_map=new TreeMap<>();
// create treemap of three array (boxes,score,classes)
float[][][]boxes =new float[1][10][4];
// 10: top 10 objects detected
// 4: coordinates in image
float[][] scores=new float[1][10];
// stores scores of 10 object
float[][] classes=new float[1][10];
// stores class of object
// add it to object_map;
output_map.put(0,boxes);
output_map.put(1,classes);
output_map.put(2,scores);
// now predict
interpreter.runForMultipleInputsOutputs(input,output_map);
Object value=output_map.get(0);
Object Object_class=output_map.get(1);
Object score=output_map.get(2);
// loop through each object
// as output has only 10 boxes
for (int i=0;i<10;i++){
float class_value=(float) Array.get(Array.get(Object_class,0),i);
float score_value=(float) Array.get(Array.get(score,0),i);
// define threshold for score
// Here you can change threshold according to your model
if(score_value>0.8){
Object box1=Array.get(Array.get(value,0),i);
// multiply it with Original height and width of frame
float top=(float) Array.get(box1,0)*height;
float left=(float) Array.get(box1,1)*width;
float bottom=(float) Array.get(box1,2)*height;
float right=(float) Array.get(box1,3)*width;
// draw rectangle in Original frame // starting point //ending point of box //color of box thickness
Imgproc.rectangle(mat_image,new Point(left,top),new Point(right,bottom),new Scalar(0, 255, 0, 255),2);
// write text on frame
// string of class name of object // starting point // color of text // size of text
Imgproc.putText(mat_image,labelList.get((int) class_value),new Point(left,top),3,1,new Scalar(255, 0, 0, 255),2);
}
}
return mat_image;
}
private ByteBuffer convertBitmapToByteBuffer(Bitmap bitmap) {
ByteBuffer byteBuffer;
int quant=1;
int size_images=INPUT_SIZE;
if(quant==0){
byteBuffer=ByteBuffer.allocateDirect(1*size_images*size_images*3);
}
else {
byteBuffer=ByteBuffer.allocateDirect(4*1*size_images*size_images*3);
}
byteBuffer.order(ByteOrder.nativeOrder());
int[] intValues=new int[size_images*size_images];
bitmap.getPixels(intValues,0,bitmap.getWidth(),0,0,bitmap.getWidth(),bitmap.getHeight());
int pixel=0;
for (int i=0;i<size_images;++i){
for (int j=0;j<size_images;++j){
final int val=intValues[pixel++];
if(quant==0){
byteBuffer.put((byte) ((val>>16)&0xFF));
byteBuffer.put((byte) ((val>>8)&0xFF));
byteBuffer.put((byte) (val&0xFF));
}
else {
byteBuffer.putFloat((((val >> 16) & 0xFF))/255.0f);
byteBuffer.putFloat((((val >> 8) & 0xFF))/255.0f);
byteBuffer.putFloat((((val) & 0xFF))/255.0f);
}
}
}
return byteBuffer;
}
}
PreviewImageActivity.java
package bline.detector.com.ffmpegvideoeditor.activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import bline.detector.com.ffmpegvideoeditor.R;
public class PreviewImageActivity extends AppCompatActivity {
private static final String FILEPATH = "filepath";
private objectDetectorClass objectDetectorClass;
private ImageSwitcher imageSwitcher;
private Button prev;
private Button next;
int placement = 0;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preview_image);
TextView tvInstruction = (TextView) findViewById(R.id.tvInstruction);
imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
prev = findViewById(R.id.prev);
next = findViewById(R.id.next);
ArrayList<Bitmap> bitmap = new ArrayList<Bitmap>();
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
ArrayList<Drawable> drawables = new ArrayList<Drawable>();
try {
objectDetectorClass = new objectDetectorClass(getAssets(), "bline_model.tflite", "bline_label.txt", 300);
Log.d("PreviewImageActivity", "Model is successfully loaded");
} catch (IOException e) {
Log.d("PreviewImageActivity", "Getting some error");
e.printStackTrace();
}
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
#Override
public View makeView() {
ImageView imageView = new ImageView(getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
return imageView;
}
});
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (placement > 0) {
placement--;
imageSwitcher.setImageDrawable(drawables.get(placement));
} else {
Toast.makeText(PreviewImageActivity.this, "No Previous Images", Toast.LENGTH_SHORT).show();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (placement < drawables.size() - 1) {
placement++;
imageSwitcher.setImageDrawable(drawables.get(placement));
} else {
Toast.makeText(PreviewImageActivity.this, "No More Images", Toast.LENGTH_SHORT).show();
}
}
});
String filePath = getIntent().getStringExtra(FILEPATH);
ArrayList<String> f = new ArrayList<String>();
File dir = new File(filePath);
tvInstruction.setText("Images stored at path " + filePath);
File[] listFile;
listFile = dir.listFiles();
for (File e : listFile) {
f.add(e.getAbsolutePath());
}
if (f != null) {
Log.d("PreviewImageAdapter", "filepath: " + f);
for (int position = 0; position < f.size(); position++) {
Bitmap bmp = BitmapFactory.decodeFile(f.get(position));
bitmap.add(bmp);
Log.d("PreviewImageAdapter", "bitmap: " + bitmap);
if (bitmap.size() == f.size()) {
for (int m = 0; m < bitmap.size(); m++) {
Mat selected_image = new Mat(bitmap.get(m).getHeight(), bitmap.get(m).getWidth(), CvType.CV_8UC4);
Utils.bitmapToMat(bitmap.get(m), selected_image);
selected_image = objectDetectorClass.recognizeVideo(selected_image);
Bitmap bitmap1 = Bitmap.createBitmap(selected_image.cols(), selected_image.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(selected_image, bitmap1);
bitmaps.add(bitmap1);
Log.d("PreviewImageAdapter", "detected images: " + bitmaps);
}
if (bitmaps.size() == bitmap.size()) {
for (int n = 0; n < bitmaps.size(); n++) {
Drawable drawable = new BitmapDrawable(bitmaps.get(n));
drawables.add(drawable);
Log.d("PreviewImageAdapter", "drawables: " + drawables);
}
}
imageSwitcher.setImageDrawable(drawables.get(0));
placement = 0;
}
}
}
}
}
I am also new to java and am sorry if my question is silly.
Hello everyone, My group for Thesis project is currently having problems on running our android app using Android Studio, The concept is Steganography and we are using an F5 Library from https://github.com/guardianproject/PixelKnot/tree/version_2/PixelKnot/src/main/java/info/guardianproject/pixelknot
Here is our user interface and whenever clicking embed button, the app closes automatically
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.angel.filepicker, PID: 2972
java.lang.NullPointerException: Attempt to invoke virtual method 'void info.guardianproject.f5android.stego.StegoProcessor.addThread(info.guardianproject.f5android.stego.StegoProcessThread, boolean)' on a null object reference
at com.example.angel.filepicker.EmbedFragment$3.onClick(EmbedFragment.java:162)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
EmbedFragment.java code
package com.example.angel.filepicker;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import info.guardianproject.f5android.plugins.f5.Embed;
import info.guardianproject.f5android.stego.*;
import info.guardianproject.f5android.plugins.PluginNotificationListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import static android.app.Activity.RESULT_OK;
public class EmbedFragment extends Fragment {
private static final String TAG = "EMbed";
public EmbedFragment() {
}
private Activity a;
public File finalFile;
public File msgFile;
public byte[] seed = new String("This is hopefully Temporary").getBytes();
public String baseimage;
public String secret_file;
public Intent fileIntent;
public static Activity act;
public static Context cntx;
public StegoProcessor stego_processor;
//FOR FILE BUTTON
public static final int FILE_PICKER_REQUEST_CODE = 1;
Intent intent;
Button btn_choose_image;
ImageView image;
TextView text;
//FOR IMAGE BUTTON
File photoFile = null;
static final int CAPTURE_IMAGE_REQUEST = 2;
static final int SELECT_FILE = 3;
String mCurrentPhotoPath;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.embed_fragment, container, false);
cntx = getActivity().getBaseContext();
act = getActivity();
//initialize and set intent type
fileIntent = new Intent();
fileIntent.setType("*/*");
fileIntent.setAction(Intent.ACTION_GET_CONTENT);
text = view.findViewById(R.id.textView2);
//FOR FILE BUTTON
Button pickButton = view.findViewById(R.id.pick_from_activity);
pickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checkPermissionsAndOpenFilePicker();
startActivityForResult(Intent.createChooser(fileIntent, "Select File"), FILE_PICKER_REQUEST_CODE);
}
});
//FOR IMAGE BUTTON
btn_choose_image = view.findViewById(R.id.btn_choose_image);
image = view.findViewById(R.id.imageView2);
btn_choose_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
final Button embedButton = (Button) view.findViewById(R.id.embedButton);
embedButton.setOnClickListener(embedButtonListener);
return view;
}
View.OnClickListener embedButtonListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if(baseimage !=null)
{
if ( secret_file != null) {
//ImageSteganography Object instantiation
Embed embed = new Embed(a,baseimage , secret_file, seed) {
#Override
public void run() {
super.run();
}
};
stego_processor.addThread(embed, true);
}
}
}
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Log.e("onActivityResult", "requestCode " + requestCode + ", resultCode " + resultCode);
if (requestCode == FILE_PICKER_REQUEST_CODE && resultCode==RESULT_OK && data != null && data.getData() != null) {
Uri uri=data.getData();
try{
msgFile=new File(uri.getPath());//get the file
secret_file = uri.getPath();
//secretFile = getPathFromUri(getActivity(),uri);
Toast.makeText(act.getBaseContext(), "Picked file: " + msgFile, Toast.LENGTH_LONG).show();
//text.setText(textx);
}catch(Exception e){}
if(msgFile.length()==0){
try{
msgFile=new File(getPathFromUri(getActivity(),uri));//get the file
// secretFile = getPathFromUri(getActivity(),uri);
Toast.makeText(act.getBaseContext(), "Picked file: " + msgFile, Toast.LENGTH_LONG).show();
}catch(Exception e){
Log.e("Main","Unable to get file!");
e.printStackTrace();
}
}
}
if (requestCode == CAPTURE_IMAGE_REQUEST && resultCode == RESULT_OK) {
// baseImage = photoFile.getAbsoluteFile();
Bitmap myBitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
}
//PROBLEMA NITO IS YUNG PAG DISPLAY NG PIC YUNG SIZE NG PIC .
// MAY METHOD NA RESIZIND PERO TSAKA NA CGURO PAG NALAGAY NA UI
if (requestCode == SELECT_FILE && data != null && data.getData() != null) {
// baseImage = getRealPathFromURI(getActivity(), data.getData());
Uri uri=data.getData();
try {
// mengambil gambar dari Gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
baseimage = uri.getPath();
image.setImageBitmap(bitmap);
text.setText(baseimage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// private String getRealPathFromURI(Context context, Uri contentUri) {
// Cursor cursor = null;
// try {
// String[] proj = { MediaStore.Images.Media.DATA };
// cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
// int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// cursor.moveToFirst();
// return cursor.getString(column_index);
// } catch (Exception e) {
// Log.e(TAG, "getRealPathFromURI Exception : " + e.toString());
// return "";
// } finally {
// if (cursor != null) {
// cursor.close();
// }
// }
// }
public static String getPathFromUri(final Context context, final Uri uri) {//get path name from a uri object(source: web)
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
//...................................................................................................................................
//FOR IMAGE BUTTON
private void captureImage() {
image.setImageResource(0);
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
//ITO YUNG CHOICE KUNG TAKE PHOTO OR SELECT IMAGE . KAPAG TAKE PHOTO DAPAT
// NASASAVE SA GALLERY PERO WALA AKO NAKITA SA GALLERY KO HAHAH FEELING KO MAS OKAY PAG DI NLNG NASSASAVE
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add Photo!");
builder.setIcon(R.mipmap.ic_launcher);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
// Create the File where the photo should go
try {
photoFile = createImageFile();
displayMessage(getActivity().getBaseContext(), photoFile.getAbsolutePath());
Log.i("Stegrapp", photoFile.getAbsolutePath());
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.example.angel.filepicker.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAPTURE_IMAGE_REQUEST);
}
} catch (Exception ex) {
// Error occurred while creating the File
displayMessage(getActivity().getBaseContext(), ex.getMessage().toString());
}
} else {
displayMessage(getActivity().getBaseContext(), "Nullll");
}
//PROBLEMA NITO IS YUNG PAG DISPLAY NG PIC YUNG SIZE NG PIC .
// MAY METHOD NA RESIZIND PERO TSAKA NA CGURO PAG NALAGAY NA UI
} else if (items[item].equals("Choose from Library")) {
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
//........................................................................................................
//ITO YUNG PAG CREATE NG FILE NUNG IMAGE GALING CAMERA
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void displayMessage(Context context, String message)
{
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
public static void show(final String toast){
act.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(EmbedFragment.cntx,toast,Toast.LENGTH_LONG).show();
}
});
}
}
MainActivity.java code
package com.example.angel.filepicker;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 4000;
ImageView imageView;
Toolbar toolbar;
ViewPager viewPager;
TabLayout tabLayout;
FloatingActionButton shareButton;
Button btn_choose_image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar_id);
viewPager = findViewById(R.id.viewPager_id);
tabLayout = findViewById(R.id.tabLayout_id);
shareButton = findViewById(R.id.shareButton_id);
//sharing
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(Intent.ACTION_SEND);
// this should be the file
// must create folder the carrier image
// this is a sample that takes string
//intent takes string should be file
myIntent.setType("text/plain");
//should be the carrier image
String shareBody = "Your body here";
// can be removed / optional
String shareSub = "Your subject here";
myIntent.putExtra(Intent.EXTRA_SUBJECT,shareSub);
myIntent.putExtra(Intent.EXTRA_TEXT,shareBody);
startActivity(Intent.createChooser(myIntent, "Share using"));
}
});
// SETTING UP ViewPagerAdapter
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addElements(new EmbedFragment(), "Embed");
viewPagerAdapter.addElements(new ExtractFragment(), "Extract");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
There are two Standard options 'Camera' and 'Gallery'. First I choose the option 'Camera', then capture the image and then edit and save.
HomeActivity.java file:
package com.saashtechs.photoeditor;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Objects;
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public class HomeActivity extends AppCompatActivity {
private static final String TAG = "HomeActivity";
private static final int GALLERY_RESULT = 1;
private static final int CAMERA_RESULT = 2;
private static final String FILE_PROVIDER_AUTHORITY = "com.saashtechs.photoeditor";
private static final int CAMERA_PERMISSION_REQ_CODE = 1001;
private static final int STORAGE_PERMISSION_REQ_CODE = 1002;
private Uri imageToUploadUri;
private String mCapturedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
public void openCamera(View view) {
// check for camera permission if not granted before
if (ContextCompat.checkSelfPermission(this, CAMERA) != PERMISSION_GRANTED) {
String[] cameraPermission = {CAMERA};
ActivityCompat.requestPermissions(this, cameraPermission, CAMERA_PERMISSION_REQ_CODE);
} else {
dispatchImageCaptureIntent();
}
}
public void openGallery(View view) {
// check for storage permission if not granted before
if (ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
String[] storagePermissions = {READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE};
ActivityCompat.requestPermissions(this, storagePermissions, STORAGE_PERMISSION_REQ_CODE);
} else {
dispatchGalleryIntent();
}
}
private void dispatchGalleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY_RESULT);
}
private void dispatchImageCaptureIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
Uri photoFileUri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, photoFile);
Log.d(TAG, "dispatchImageCaptureIntent:photoFileUri: " + photoFile.toString());
imageToUploadUri = photoFileUri;
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFileUri);
startActivityForResult(cameraIntent, CAMERA_RESULT);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CAMERA_PERMISSION_REQ_CODE:
if (grantResults[0] == PERMISSION_GRANTED) {
dispatchImageCaptureIntent();
} else {
Toast.makeText(this, "Required camera permission not granted", Toast.LENGTH_SHORT).show();
}
break;
case STORAGE_PERMISSION_REQ_CODE:
if (grantResults[0] == PERMISSION_GRANTED) {
dispatchGalleryIntent();
} else {
Toast.makeText(this, "Required storage permission not granted", Toast.LENGTH_SHORT)
.show();
}
break;
default:
throw new IllegalArgumentException("Unexpected request code");
}
}
private File createImageFile() throws IOException {
String timeStamp = DateFormat.getDateTimeInstance().format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
mCapturedImagePath = image.getAbsolutePath();
Log.d(TAG, "createImageFile: " + mCapturedImagePath);
return image;
}
private Bundle uriToBundle(Uri imageUri) {
Bundle bundle = new Bundle();
bundle.putString(MainActivity.IMAGE_URI, imageUri.toString());
return bundle;
}
public Bitmap resizeBitmap(Bitmap getBitmap, int maxSize) {
int width = getBitmap.getWidth();
int height = getBitmap.getHeight();
double resized_image;
if (width >= height && width > maxSize) {
resized_image = width / height;
width = maxSize;
height = (int) (maxSize / resized_image);
} else if (height >= width && height > maxSize) {
resized_image = height / width;
height = maxSize;
width = (int) (maxSize / resized_image);
}
return Bitmap.createScaledBitmap(getBitmap, width, height, false);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == GALLERY_RESULT) {
Uri imageUri = data.getData();
startActivity(MainActivity.getIntent(this, uriToBundle(Objects.requireNonNull(imageUri))));
} else if (requestCode == CAMERA_RESULT) {
File imageFile = new File(mCapturedImagePath);
Bitmap image = BitmapFactory.decodeFile(mCapturedImagePath);
image = Bitmap.createScaledBitmap(image, 4477, 3351, false);
image = resizeBitmap(image, 4477);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "filename.jpg");
boolean result;
result = file.createNewFile();
if (result) {
FileOutputStream fo = new FileOutputStream(imageFile);
fo.write(bytes.toByteArray());
fo.close();
}
} catch(IOException ie) {
ie.printStackTrace();
}
startActivity(MainActivity.getIntent(this, uriToBundle(Objects.requireNonNull(imageToUploadUri))));
}
} else {
Toast.makeText(this, "Image not loaded.", Toast.LENGTH_SHORT).show();
}
}
public static Intent getIntent(Context context) {
return new Intent(context, HomeActivity.class);
}
}
When the app is used for the first time, after image is captured, the folder is not getting created for the saved image to be stored in Gallery/Photos app. If I use 'Gallery' as the option to save the image, folder gets created. After the folder gets created, then if I capture the image, the captured image gets stored since folder is already created through 'Gallery' option
Can anyone please help?
Thanks in advance
How about changing File imageFile = new File(mCapturedImagePath); with
File imageFile = new File(intent.getData());
mCapturedImagePath is always empty when activityResult is being called. you would need to get the image path from the intent and then get a File instance from the path or uri. intent#getData() returns the uri of the image.
I'm creating an Android app to capture image when input the wrong password so I created Camera class & Launcher class:
Camera.java
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Camera extends Activity{
private static final int CAMERA_REQUEST = 1888;
private static final int ACTION_TAKE_PHOTO = 1;
ImageView mimageView;
String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private boolean hasCamera() {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FRONT)){
return true;
} else {
return false;
}
}
private void takePicture(int actionCode){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch (actionCode){
case ACTION_TAKE_PHOTO:
boolean front_camera = hasCamera();
File f = null;
try {
if (front_camera){
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
}
else {
return;
};
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
}
startActivityForResult(intent,CAMERA_REQUEST);
mimageView.setVisibility(View.INVISIBLE);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
mimageView.setImageBitmap(mphoto);
takePicture(ACTION_TAKE_PHOTO);
}
}
}
Launcher.java
import android.app.KeyguardManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.Vector;
public class Launcher extends Service implements View.OnClickListener, View.OnTouchListener{
WindowManager windowManager;
WindowManager.LayoutParams layoutparams;
RelativeLayout relativeLayout;
TextView text;
String password;
String password_saved;
String hint;
Vector<Long> hold_time;
long down_time[];
Vector<Vector<Float>> pressure;
Vector pressure_num[];
Vector<Vector<Float>> size;
Vector size_num[];
Button nums[]=null;
ImageButton clear;
ImageButton ok;
Vector<Vector<Float>> vecs;
Vector<Float> H_2;
#Override
public IBinder onBind(Intent intent){
return null;
}
#Override
public void onCreate(){
super.onCreate();
Log.d("Launcher","onCreate()");
KeyguardManager.KeyguardLock keyguardLock;
KeyguardManager keyguardManager=(KeyguardManager)getSystemService(KEYGUARD_SERVICE);
keyguardLock=keyguardManager.newKeyguardLock("");
keyguardLock.disableKeyguard();
IntentFilter intentFilter=new IntentFilter("android.intent.action.SCREEN_OFF");
intentFilter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(screenReceiver, intentFilter);
setUpLayout();
}
#Override
public int onStartCommand(Intent intent,int flags,int startId){
return Service.START_STICKY;
}
#Override
public void onDestroy(){
unregisterReceiver(screenReceiver);
Log.d("Service","Service stop!!!");
// startActivity(new Intent(Launcher.this,Launcher.class));
// KeyguardManager.KeyguardLock keyguardLock;
// KeyguardManager keyguardManager=(KeyguardManager)getSystemService(KEYGUARD_SERVICE);
// keyguardLock=keyguardManager.newKeyguardLock("");
// keyguardLock.reenableKeyguard();
super.onDestroy();
}
private BroadcastReceiver screenReceiver=new BroadcastReceiver() {
public boolean wasScreenOn=true;
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
Log.d("Launcher","action is "+action);
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
wasScreenOn=false;
launchLock();
}else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
wasScreenOn=true;
}else if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
launchLock();
}
}
};
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
public int spTpPx(int sp) {
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
return Math.round(sp * displayMetrics.scaledDensity);
}
private void setUpLayout(){
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
layoutparams= new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.RGBA_8888
);
nums=new Button[10];
relativeLayout = new RelativeLayout(this);
relativeLayout.setBackgroundResource(R.drawable.back);
int marginPix=dpToPx(-16);
int paddingPix=dpToPx(20);
RelativeLayout.LayoutParams params[]=new RelativeLayout.LayoutParams[10];
for (int i=0;i<10;i++){
params[i]=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
params[i].bottomMargin=marginPix;
nums[i]=new Button(this);
nums[i].setId(i);
nums[i].setPadding(paddingPix, paddingPix, paddingPix, paddingPix);
nums[i].setTextSize(TypedValue.COMPLEX_UNIT_SP, 35);
nums[i].setTypeface(null, Typeface.NORMAL);
nums[i].setTextColor(Color.parseColor("#a0333333"));
nums[i].setBackgroundColor(Color.parseColor("#00000000"));
nums[i].setOnClickListener(this);
nums[i].setOnTouchListener(this);
}
params[2].addRule(RelativeLayout.CENTER_IN_PARENT);
nums[2].setText(R.string.num_2);
params[5].addRule(RelativeLayout.CENTER_HORIZONTAL);
params[5].addRule(RelativeLayout.BELOW, 2);
nums[5].setText(R.string.num_5);
params[1].addRule(RelativeLayout.LEFT_OF, 2);
params[1].addRule(RelativeLayout.ABOVE,5);
nums[1].setText(R.string.num_1);
params[3].addRule(RelativeLayout.RIGHT_OF, 2);
params[3].addRule(RelativeLayout.ABOVE, 5);
nums[3].setText(R.string.num_3);
params[4].addRule(RelativeLayout.LEFT_OF, 2);
params[4].addRule(RelativeLayout.BELOW,2);
nums[4].setText(R.string.num_4);
params[6].addRule(RelativeLayout.RIGHT_OF, 2);
params[6].addRule(RelativeLayout.BELOW, 2);
nums[6].setText(R.string.num_6);
params[7].addRule(RelativeLayout.LEFT_OF, 5);
params[7].addRule(RelativeLayout.BELOW,5);
nums[7].setText(R.string.num_7);
params[8].addRule(RelativeLayout.BELOW, 5);
params[8].addRule(RelativeLayout.RIGHT_OF,4);
nums[8].setText(R.string.num_8);
params[9].addRule(RelativeLayout.BELOW, 5);
params[9].addRule(RelativeLayout.RIGHT_OF,5);
nums[9].setText(R.string.num_9);
params[0].addRule(RelativeLayout.BELOW, 8);
params[0].addRule(RelativeLayout.RIGHT_OF,7);
nums[0].setText(R.string.num_0);
RelativeLayout.LayoutParams clear_param=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
clear_param.addRule(RelativeLayout.BELOW,8);
clear_param.addRule(RelativeLayout.LEFT_OF, 8);
clear_param.setMargins(0, dpToPx(6), dpToPx(12), 0);
clear=new ImageButton(this);
clear.setId(R.id.clear);
clear.setImageResource(R.drawable.ic_action_cancel);
clear.setBackgroundColor(Color.parseColor("#00000000"));
clear.setPadding(paddingPix, paddingPix, paddingPix, paddingPix);
clear.setLayoutParams(clear_param);
clear.setOnClickListener(this);
RelativeLayout.LayoutParams ok_param=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
ok_param.addRule(RelativeLayout.BELOW,8);
ok_param.addRule(RelativeLayout.RIGHT_OF, 8);
ok_param.setMargins(dpToPx(12), dpToPx(6), 0, 0);
ok=new ImageButton(this);
ok.setId(R.id.ok);
ok.setImageResource(R.drawable.ic_action_accept);
ok.setBackgroundColor(Color.parseColor("#00000000"));
ok.setPadding(paddingPix, paddingPix, paddingPix, paddingPix);
ok.setLayoutParams(ok_param);
ok.setOnClickListener(this);
RelativeLayout.LayoutParams text_param=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
text_param.addRule(RelativeLayout.CENTER_HORIZONTAL);
text_param.addRule(RelativeLayout.ABOVE,2);
text=new TextView(this);
text.setId(R.id.text);
text.setLayoutParams(text_param);
text.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
text.setTypeface(null, Typeface.NORMAL);
text.setTextColor(Color.parseColor("#a0333333"));
text.setBackgroundColor(Color.parseColor("#00000000"));
text.setPadding(dpToPx(30),dpToPx(30),dpToPx(30),dpToPx(30));
for (int i=0;i<10;i++){
nums[i].setLayoutParams(params[i]);
}
for (int i=0;i<10;i++){
relativeLayout.addView(nums[i]);
}
relativeLayout.addView(clear);
relativeLayout.addView(ok);
relativeLayout.addView(text);
}
private void launchLock(){
try {
//load password and vecs from file
FileInputStream fileInputStream=openFileInput("password");
ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
password_saved=(String)objectInputStream.readObject();
vecs=(Vector<Vector<Float>>)objectInputStream.readObject();
H_2=(Vector<Float>)objectInputStream.readObject();
Log.d("password_saved",password_saved);
Log.d("vecs",vecs.toString());
Log.d("H_2",H_2.toString());
objectInputStream.close();
fileInputStream.close();
} catch (FileNotFoundException e) {
Log.d("window manager", "file not found");
try{
windowManager.removeView(relativeLayout);
}catch (IllegalArgumentException e1){
Log.d("window manager","has no layout");
}
return;
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
password="";
hint="";
hold_time=new Vector<Long>();
down_time=new long[10];
pressure=new Vector<Vector<Float>>();
pressure_num=new Vector[10];
size=new Vector<Vector<Float>>();
size_num=new Vector[10];
text.setText(hint);
for (int i=0;i<10;i++){
pressure_num[i]=new Vector<Float>();
size_num[i]=new Vector<Float>();
}
try {
windowManager.addView(relativeLayout,layoutparams);
}catch (RuntimeException e){
// e.printStackTrace();
Log.d("window manager","layout has already been added");
}
}
#Override
public void onClick(View view) {
int id=view.getId();
if (id==R.id.ok){
Log.d("launcher","ok");
Log.d("password",password);
Log.d("hold time",hold_time.toString());
Log.d("pressure",pressure.toString());
Log.d("size",size.toString());
try {
//turn password to md5
byte[] bytes = password.getBytes("UTF-8");
MessageDigest md=MessageDigest.getInstance("MD5");
bytes=md.digest(bytes);
password=new String(bytes);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Vector<Float> vec=new Vector<Float>();
for (long value:hold_time){
vec.add((float) value);
}
for (Vector<Float> values:pressure){
vec.add(Collections.max(values));
}
for (Vector<Float> values:size){
vec.add(Collections.max(values));
}
Log.d("vec",vec.toString());
Log.d("MD5",password);
boolean quit=true;
//if password is equal
Vector<Float> probs=new Vector<Float>();
if (password.equals(password_saved)){
for (int i=0;i<H_2.size();i++){
float p=0;
for (int j=0;j<vecs.size();j++){
//np.exp(-1./2.*(v_test[i]-v_train[i])**2/H_2[i])
p+=Math.exp(-1./2.*
(vec.elementAt(i)-vecs.elementAt(j).elementAt(i))*
(vec.elementAt(i)-vecs.elementAt(j).elementAt(i))/
H_2.elementAt(i)
);
}
p/=vecs.size();
probs.add(p*p);
}
Log.d("probs ",probs.toString());
Float sum_probs= new Float(0);
for (int i=0;i<probs.size()/3*2;i++){
sum_probs+=probs.elementAt(i);
}
Log.d("sum_probs ",sum_probs.toString());
if (sum_probs<0.25*probs.size()/3*2)
quit=false;
}else{
quit=false;
}
if (quit)
windowManager.removeView(relativeLayout);
else{
//if fail, then init
text.setText("Wrong password");
hint="";
password="";
hold_time=new Vector<Long>();
pressure=new Vector<Vector<Float>>();
size=new Vector<Vector<Float>>();
}
}else if (id==R.id.clear){
text.setText("Please enter again");
hint="";
password="";
hold_time=new Vector<Long>();
pressure=new Vector<Vector<Float>>();
size=new Vector<Vector<Float>>();
}else {
text.setText(hint+="*");
password+=Integer.toString(id);
Log.d("password",password);
}
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int id=view.getId();
if(motionEvent.getActionMasked()==MotionEvent.ACTION_DOWN){
down_time[id]= SystemClock.uptimeMillis();
pressure_num[id]=new Vector<Float>();
size_num[id]=new Vector<Float>();
}else if(motionEvent.getActionMasked()==MotionEvent.ACTION_UP){
hold_time.add(SystemClock.uptimeMillis()-down_time[id]);
pressure.add((Vector<Float>)pressure_num[id]);
size.add((Vector<Float>)size_num[id]);
}
pressure_num[id].add(motionEvent.getPressure());
size_num[id].add(motionEvent.getSize());
return false;
}
}
The problem is that I don't know how to call Camera class in Launcher class
In my application there is a button to "upload a picture": taking a photo from camera or choosing from gallery.
On both options, there are 3 problems:
1) When clicking again to upload another picture - the application crushes
2) On the first "upload", the picture is rotated on the side (90 degrees counterclockwise)
3) The picture's size is the original size and I want it to be compressed to resolution of 125x125.
Please help (even if you have a solution to one problem)
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import entities.Order;
public class SellABookFragment extends Fragment implements View.OnClickListener {
private ImageView ivBookPicture;
private EditText etBookName, etBookAuthor, etBookGenre, etBookPublishing, etQuantity, etBookPrice, etBookDetails;
private Button bUploadPicture, bAddBook;
public SellABookFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sell_a_book, container, false);
ivBookPicture = (ImageView) view.findViewById(R.id.ivBook_Picture);
etBookName = (EditText) view.findViewById(R.id.etBook_Name);
etBookAuthor = (EditText) view.findViewById(R.id.etAuthor_Name);
etBookGenre = (EditText) view.findViewById(R.id.etGenre);
etBookPublishing = (EditText) view.findViewById(R.id.etPublishing_Year);
etQuantity = (EditText) view.findViewById(R.id.etBook_Quantity);
etBookPrice = (EditText) view.findViewById(R.id.etBook_Price);
etBookDetails = (EditText) view.findViewById(R.id.etBook_Details);
bUploadPicture = (Button) view.findViewById(R.id.bUpload_Picture);
bAddBook = (Button) view.findViewById(R.id.bAdd_Book);
bUploadPicture.setOnClickListener(this);
bAddBook.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bUpload_Picture:
selectPicture();
break;
case R.id.bAdd_Book:
addBook();
break;
}
}
private void addBook() {
try {
HomeActivity.backEnd.addOrder(new Order(HomeActivity.LoggedUser.getID(),
etBookGenre.getText().toString(),
etBookName.getText().toString(),
Integer.parseInt(etBookPublishing.getText().toString()),
etBookAuthor.getText().toString(),
Double.parseDouble(etBookPrice.getText().toString()),
(Integer) ivBookPicture.getTag()));
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void selectPicture() {
final CharSequence[] options = {
getResources().getString(R.string.take_photo),
getResources().getString(R.string.gallery_choose),
getResources().getString(R.string.cancel)};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(R.string.upload_picture));
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals(getResources().getString(R.string.take_photo))) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "tmp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals(getResources().getString(R.string.gallery_choose))) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else
dialog.dismiss();
}
});
builder.show();
}
Bitmap bitmap;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
OutputStream outFile;
String path = android.os.Environment.getExternalStorageDirectory()
+ File.separator
+ "MyApp";
File file;
if (resultCode == Activity.RESULT_OK) {
if (bitmap != null) {
ivBookPicture.setImageBitmap(null);
bitmap.recycle();
bitmap = null;
}
try {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File tmp : f.listFiles()) {
if (tmp.getName().equals("tmp.jpg")) {
f = tmp;
break;
}
}
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
ivBookPicture.setImageBitmap(bitmap);
if (f.delete()) {
file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getActivity().getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
bitmap = (BitmapFactory.decodeFile(picturePath));
Log.w("image path", picturePath);
ivBookPicture.setImageBitmap(bitmap);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The ImageView which contains the uploaded picture:
<ImageView
android:id="#+id/ivBook_Picture"
android:layout_width="#dimen/sell_a_book_picture_size"
android:layout_height="#dimen/sell_a_book_picture_size"
android:src="#mipmap/ic_launcher" />
Thanks!
public Bitmap compressBySize(String pathName, int targetWidth,
int targetHeight) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
int imgWidth = opts.outWidth;
int imgHeight = opts.outHeight;
int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
if (widthRatio > 1 || heightRatio > 1) {
if (widthRatio > heightRatio) {
opts.inSampleSize = widthRatio;
} else {
opts.inSampleSize = heightRatio;
}
}
opts.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(pathName, opts);
return bitmap;
}
Use this method to do the compress,just set the targetWidth&targetHeight yourself.
Also,you can use bitmap.compress(Bitmap.CompressFormat.JPEG, compressRate, byteOutputStream); to compress your bitmap by quality.
For the crash,it's because the picture bitmap takes too much memory.You should compress the picture and remember to release the memory after your first upload.You can consider using a WeakReference.