Android Studio Camera App Saving to Internal Storage - java

Currently looking for help on saving images from a camera app to internal storage do to Nexus not having an SD card, our current code saves the photos taken to an SD card folder and the quality is not good.
public class MainActivity extends ActionBarActivity {
private ImageView imageHolder;
private final int requestCode = 20;
public final static String EXTRA_MESSAGE = "com.test1.cam.camapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageHolder = (ImageView)findViewById(R.id.captured_photo);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);
// display the image from SD Card to ImageView Control
String storeFilename = "photo_" + partFilename + ".jpg";
Bitmap mBitmap = getImageFileFromSDCard(storeFilename);
imageHolder.setImageBitmap(mBitmap);
}
}
public void showGreetings(View view)
{
String button_text;
button_text = ((Button) view) .getText().toString();
if(button_text.equals("Info"))
{
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
else if (button_text.equals("Info"))
{
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
public void saveImage(Context context, Bitmap b,String name,String extension){
name=name+"."+extension;
FileOutputStream out;
try {
out = context.openFileOutput(name, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Bitmap getImageFileFromSDCard(String filename){
Bitmap bitmap = null;
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
try {
FileInputStream fis = new FileInputStream(imageFile);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

To improve the image quality you should change compression to PNG, or change the second parameters to 100 (PNG is lossless and will ignore second params).
b.compress(Bitmap.CompressFormat.PNG, 100, out);
To change external into internal just change
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
into
File outputFile = new File(context.getFilesDir(), "photo_" + currentDate + ".jpg");

The image you are trying to save returns you jest the thumbnail of the actual image that is why you are getting low quality image. You should pass the image name to the intent to save the high quality image when it is captured
Following Helper class that I use for image capture may be of some help to you
public class CaptureImageHelper {
private static final int DEFAULT_WIDTH = 1024; // min pixels
private static final int DEFAULT_HEIGHT = 768; // min pixels
private static final String TEMP_IMAGE_NAME = "tempImage";
public static Intent getImageCaptureIntent(Context context, String title) {
Intent chooserIntent = null;
List<Intent> intentList = new ArrayList<>();
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
intentList = addIntentsToList(context, intentList, takePhotoIntent);
if (intentList.size() > 0) {
chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1), title);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
}
return chooserIntent;
}
private static File getTempFile(Context context) {
//Note you can change the path here according to your need
File imageFile = new File(Environment.getExternalStorageDirectory(), TEMP_IMAGE_NAME);
imageFile.getParentFile().mkdirs();
return imageFile;
}
private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resInfo) {
String packageName = resolveInfo.activityInfo.packageName;
Intent targetedIntent = new Intent(intent);
targetedIntent.setPackage(packageName);
list.add(targetedIntent);
}
return list;
}
public static Bitmap getImageFromResult(Context context, int resultCode, Intent imageReturnedIntent) {
return getImageFromResult(context, DEFAULT_WIDTH, DEFAULT_HEIGHT, resultCode, imageReturnedIntent);
}
public static Bitmap getImageFromResult(Context context, int width, int height, int resultCode, Intent imageReturnedIntent) {
Bitmap bm = null;
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage;
File imageFile = getTempFile(context);
selectedImage = Uri.fromFile(imageFile);
bm = getImageResized(context, selectedImage, width, height);
int rotation = getRotation(context, selectedImage, true);
bm = rotate(bm, rotation);
}
return bm;
}
private static Bitmap getImageResized(Context context, Uri selectedImage, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
System.gc();
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap actuallyUsableBitmap = null;
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getContentResolver().openAssetFileDescriptor(selectedImage, "r");
} catch (FileNotFoundException e) {
}
if (null != fileDescriptor) {
BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
actuallyUsableBitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
}
return actuallyUsableBitmap;
}
private static Bitmap getImageResized(Context context, Uri selectedImage) {
return getImageResized(context, selectedImage, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private static int getRotation(Context context, Uri imageUri, boolean isCamera) {
int rotation;
if (isCamera) {
rotation = getRotationFromCamera(context, imageUri);
} else {
rotation = getRotationFromGallery(context, imageUri);
}
return rotation;
}
private static int getRotationFromCamera(Context context, Uri imageFile) {
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageFile, null);
ExifInterface exif = new ExifInterface(imageFile.getPath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
private static int getRotationFromGallery(Context context, Uri imageUri) {
int orientation = 0;
String[] columns = {MediaStore.Images.Media.ORIENTATION};
Cursor cursor = context.getContentResolver().query(imageUri, columns, null, null, null);
if (null != cursor && cursor.moveToFirst()) {
int orientationColumnIndex = cursor.getColumnIndex(columns[0]);
orientation = cursor.getInt(orientationColumnIndex);
cursor.close();
}
return orientation;
}
private static Bitmap rotate(Bitmap bm, int rotation) {
if (rotation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
return Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
}
return bm;
}
}

Related

Multiple Images from Gallery convert to PDF

Hi can someone help me how can I add to pdf the selected images from gallery? I already have working code but it can only convert one bitmap.
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void createPdf(){
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = displaymetrics.heightPixels ;
float width = displaymetrics.widthPixels ;
int convertHighet = (int) hight, convertWidth = (int) width;
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ffffff"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0 , null);
document.finishPage(page);
// write the document content
String targetPdf = "/sdcard/test.pdf";
File filePath = new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
btn_convert.setText("Check PDF");
boolean_save=true;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
}
// close the document
document.close();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICTURE && resultCode == RESULT_OK) {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
if(uri != null) {
Cursor cursor = getContentResolver().query(uri, new String[] {
android.provider.MediaStore.Images.ImageColumns.DATA},
null, null, null);
cursor.moveToFirst();
String imageFilePath = cursor.getString(0);
cursor.close();
iv_image.setImageURI(uri);
encodedImage = imageFilePath;
} else {
tv_Load.setText("There's an error");
}
}
}
These are my declarations/fields.
public static final int GALLERY_PICTURE = 1;
public static final int REQUEST_PERMISSIONS = 1;
Button btn_select, btn_convert, btn_upload;
Bitmap bitmap;
Here's my code now that can select Multiple Image but can't convert bitmaps to pdf. It saves but it says PDF is of Invalid Format.
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICTURE && resultCode == RESULT_OK) {
if (resultCode == RESULT_OK) {
final List<Bitmap> bitmaps = new ArrayList<>();
ClipData clipData = data.getClipData();
if (clipData != null) {
for (int i = 0; i < clipData.getItemCount(); i++) {
Uri imageUri = clipData.getItemAt(i).getUri();
try {
InputStream is = getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
bitmaps.add(bitmap);
bitmapcount = clipData.getItemCount();
Toast.makeText(getApplicationContext(),"Image Selected: " + clipData.getItemCount(), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else {
Uri imageUri = data.getData();
try {
InputStream is = getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
bitmaps.add(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
new Thread(new Runnable() {
#Override
public void run() {
for (final Bitmap b : bitmaps) {
runOnUiThread(new Runnable() {
#Override
public void run() {
iv_image.setImageBitmap(b);
}
});
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void createPdf(){
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = displaymetrics.heightPixels ;
float width = displaymetrics.widthPixels ;
int convertHighet = (int) hight, convertWidth = (int) width;
PdfDocument document = new PdfDocument();
if (bitmapcount > 1){
for(int i = 0; i < bitmapcount; i++ ){
try {
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), i).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ffffff"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0 , null);
document.finishPage(page);
i++;
} catch (Exception e){
e.printStackTrace();
}
}
}
//document content311
String directory_path = Environment.getExternalStorageDirectory().getPath() + "/mypdf/";
File file = new File(directory_path);
if (!file.exists()) {
file.mkdirs();
}
String targetPdf = directory_path + "JO-" + editText.getText().toString() + ".pdf";
File filePath = new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
btn_convert.setText("Check PDF");
boolean_save=true;
pdfPath = filePath.getPath();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
}
// close the document
document.close();
}
Fields
private static int bitmapcount = 0;
public static final int GALLERY_PICTURE = 1;
public static final int REQUEST_PERMISSIONS = 1;
Button btn_select, btn_convert, btn_upload;
Bitmap bitmap;

RecyclerView take Image form camera is rotating when show on the list

I have an issue with my code. When I take a photo from my app, it is rotating 90ยบ to show. But, when I choose gallery option to select my photo, it is showing normal.
Can someone help me??
Code bellow:
Adapter.java
public void onBindViewHolder(#NonNull final ProdutosListaViewHolder holder, final int i){
Produto prod = produtos.get(i);
File foto = mPicture.getImageProduto(prod.codProd);
if(foto == null || foto.exists()){
holder.foto.setImageResource(R.drawable.sem_foto_icon);
}else{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeFile(foto.getAbsolutePath(), options);
holder.foto.setImageBitmap(bitmap);
}
}
PictureManager.java
if the camera selected to take the photo
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
i.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(ctx, ....));
((Activity) ctx).startActivityForResult(i, 999);
if the gallery selected to take the photo
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
((Activity) ctx).startActivityForResult(i, 998);
ProductListActivity.java
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==999){
try{
File foto = (new PictureManager(FOTO_PRODUTO, ctx)).getImageProduto(produtoSelecionado.codProd);
if(foto != null){
mProdutosListaAdapter.notifyItemChanged(posicaoSelecionada);
}
}catch(Exception e){
e.printStackTrace();
}
}else if(requestCode==998){
try{
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = ctx.getContentResolver().query(selectedImage, filePathColumn, null null, null);
cursor.moveToFirst();
int columnIndex = cursor.ColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
File file = new File(picturePath);
int codigo = produtoSelecionado.codProd;
File foto = (new PictureManager(FOTO_PRODUTO, ctx)).salvarFoto(file, codigo, 1);
mProdutosListaAdapter.notifyDataSetChanged();
}
}
}
}
}
Camera always gives you the picture according to camera orientation. I have tried the below code to change orientation
public static Bitmap rotateImageOrientation(String photoFilePath) {
// Create and configure BitmapFactory
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photoFilePath, bounds);
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(photoFilePath, opts);
// Read EXIF Data
ExifInterface exif = null;
try {
exif = new ExifInterface(photoFilePath);
} catch (IOException e) {
e.printStackTrace();
}
String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
int rotationAngle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;
// Rotate Bitmap
Matrix matrix = new Matrix();
matrix.setRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
return Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);
// Return result
}

ImageView remains blank, Android

I am allowing user to choose image and using it to set as imageview in another activity. But the imageview remains blank. Following is my code.
private static final int REQUEST_CODE_GALLERY = 1;
private static final int REQUEST_IMAGE_CAPTURE = 2;
public ImageView CameraButton;
public ImageView GalleryButton;
public ImageView example;
public Bitmap imageBitmap;
public Bitmap bmp;
ongallery object = new ongallery();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GalleryButton = (ImageView) findViewById(R.id.GalleryButton);
CameraButton = (ImageView) findViewById(R.id.CameraButton);
example = (ImageView) findViewById(R.id.example);
GalleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, REQUEST_CODE_GALLERY);
}
});
CameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (camera.resolveActivity(getPackageManager()) != null) {
startActivityForResult(camera, REQUEST_IMAGE_CAPTURE);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && null != data) {
Uri chosen = data.getData();
String[] filepath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(chosen, filepath, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filepath[0]);
String photoadd = cursor.getString(columnIndex);
cursor.close();
bmp = BitmapFactory.decodeFile(photoadd);
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bmp.recycle();
//Pop intent
Intent in1 = new Intent(this, ongallery.class);
in1.putExtra("picture", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
}
else if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK && null!=data) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
photo.recycle();
//Pop intent
Intent in1 = new Intent(this, ongallery.class);
in1.putExtra("picture", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
}
}catch(Exception e){
Toast.makeText(this,"Something went wrong",Toast.LENGTH_SHORT).show();
}
}
}
//ongallery.java
public class ongallery extends Activity {
public ImageView imgView;
int xDim;
int yDim;
String filename;
public Bitmap finale = null ;
public Bitmap bmp = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ongallery);
imgView = (ImageView) findViewById(R.id.imgView);
filename = getIntent().getStringExtra("picture");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
imgView.setImageBitmap(decoder(filename,400,400));
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
xDim=imgView.getWidth();
yDim=imgView.getHeight();
}
public Bitmap decoder(String filename, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
finale = BitmapFactory.decodeFile(filename, options);
return finale;
}
int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) {
int inSampleSize = 1;
if (options.outHeight > reqHeight || options.outWidth > reqWidth) {
final int halfHeight = options.outHeight / 2;
final int halfWidth = options.outWidth / 2;
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) >reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
BitmapFactory.decodeFile() needs the complete path name as the first argument.
public Bitmap decoder(String filename, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
String filepath = getFileStreamPath(filename).getPath();
BitmapFactory.decodeFile(filepath, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
finale = BitmapFactory.decodeFile(filepath, options);
return finale;
}

How to select more than one photo from the gallery?

I'm building a GIF Creator for my graduation project. What it is, when I try to select from the gallery a photo it just gets it to the view, I want to select more than one photo simultaneously not to go to select photo to get another picture. As well as that I've created a button so if the user changes their mind they can delete and start from scratch not having to restart the application however I don't know what the code is for that.
The main activity:
public class MainActivity extends AppCompatActivity {
/**
* this is the destination of the new GIF file, it will be saved directly in the SD card
* (internal storage) in a file named "test.gif"
*/
private static final String IMAGE_PATH = "/sdcard/test.gif";
private static final int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private boolean zoomOut = false;
private Button btnSelect;
private LinearLayout root;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
root = (LinearLayout) findViewById(R.id.ll);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ImageView ivImage = (ImageView) findViewById(R.id.ivImage);
ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (root.getChildCount() == 0) {
return;
}
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(IMAGE_PATH);
outStream.write(generateGIF());
outStream.close();
Toast.makeText(MainActivity.this,
"GIF saved to " + IMAGE_PATH, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outStream != null) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"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("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/* video/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
Bitmap resized = Bitmap.createScaledBitmap(thumbnail, 800, 150, true);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageView ivImage = new ImageView(this);
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
gd.setStroke(1, 0xFF000000);
ivImage.setBackground(gd);
// the following code causes a crash "NullPointerException" :
// Point point = null; // --> the reason for the crash
// getWindowManager().getDefaultDisplay().getSize(point);
// int width = point.x;
// int height = point.y;
//
// ivImage.setMinimumWidth(width);
// ivImage.setMinimumHeight(height);
//
// ivImage.setMaxWidth(width);
// ivImage.setMaxHeight(height);
// ivImage.getLayoutParams().width = 20; // --> another crash happens here
// ivImage.getLayoutParams().height = 20;
ivImage.setLayoutParams(new ActionBar.LayoutParams(
GridLayout.LayoutParams.WRAP_CONTENT,
GridLayout.LayoutParams.MATCH_PARENT));
ivImage.setImageBitmap(thumbnail);
root.addView(ivImage);
// setContentView(root);
// ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
final ImageView ivImage = new ImageView(this);
ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (zoomOut) {
Toast.makeText(getApplicationContext(), "NORMAL SIZE!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ivImage.setAdjustViewBounds(true);
zoomOut = false;
} else {
Toast.makeText(getApplicationContext(), "FULLSCREEN!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
ivImage.setScaleType(ImageView.ScaleType.FIT_XY);
zoomOut = true;
}
}
});
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
ivImage.setMinimumWidth(width);
ivImage.setMinimumHeight(height);
ivImage.setMaxWidth(width);
ivImage.setMaxHeight(height);
ivImage.setLayoutParams(new ActionBar.LayoutParams(
1000,
1000));
ivImage.setImageBitmap(bm);
root.addView(ivImage);
setContentView(root);
ivImage.setImageBitmap(bm);
}
private byte[] generateGIF() {
ArrayList<Bitmap> bitmaps = new ArrayList<>();
View v;
ImageView iv;
for (int i = 0; i < root.getChildCount(); i++) {
v = root.getChildAt(i);
if (v instanceof ImageView) {
iv = (ImageView) v;
bitmaps.add(((BitmapDrawable) iv.getDrawable()).getBitmap());
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
}
You can use custom library for multiple image pick like
1) MultiSelectRecyclerGalleryGridView
2) MultipleImagePick
like Kyle Shank answered
https://stackoverflow.com/a/19848052/5090511
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Or you can use something like that:
https://github.com/luminousman/MultipleImagePick

Saving an image with its thumb and showing on imageView android

I am trying to save an image taken from camera and then storing it on sdCard along with its Thumb also showing this thumb on an imageView.
However it gives error at Null pointer
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, 40, 40, false);
What is wrong?
{
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try
{
if (title.getText().toString().equals(""))
{
displayAlert("Please Input Title First","Error!");
}
else
{
Integer val = myMisc.miscId ;
String fileName = "image" + "_" + title.getText().toString()+"_" + val.toString();
photo = this.createFile(fileName, ".jpg");
myMisc.filename = photo.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
startActivityForResult(intent, RESULT_CAMERA_SELECT);
}
}
catch(Exception e)
{
Log.v("Error", "Can't create file to take picture!");
displayAlert("Can't create file to take picture!","SDCard Error!");
}
}
public synchronized void onActivityResult(final int requestCode, int resultCode, final Intent data)
{
if (resultCode == Activity.RESULT_OK)
{
if (requestCode == RESULT_CAMERA_SELECT)
{
try
{
saveImage();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
public void saveImage() throws IOException
{
try
{
FileInputStream is2 = new FileInputStream(photo);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap imageBitmap = BitmapFactory.decodeStream(is2, null, options);
options.inSampleSize = calculateInSampleSize(options, 40, 40);
options.inJustDecodeBounds = false;
imageBitmap = BitmapFactory.decodeStream(is2 ,null, options);
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, 40, 40, false);
Integer val = myMisc.miscId;
String fileName = ".thumbImage" + "_" + title.getText().toString()+ "_" + val.toString();
photo = this.createFile(fileName, ".jpg");
myMisc.thumbFileName = photo.getAbsolutePath();
try {
FileOutputStream out = new FileOutputStream(photo);
imageBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
is2.close();
Uri uri = Uri.fromFile(photo);
photo = null;
imageBitmap = null;
imageView.setImageURI(uri);
}catch(Exception e)
{
displayAlert("Can't create file to take picture!","SD Card Error");
}
}
It's probably because of the decodeStream method.
Bitmap imageBitmap = BitmapFactory.decodeStream(is2, null, options);
You parsed null at the when it asks for a Rectangle and when you tried to create a scaled bitmap it was not valid.
i found my error Bitmap imageBitmap = BitmapFactory.decodeStream(is2, null, options); decoding twice

Categories

Resources