There are quite a few similar topics and issues around here and I follow this . But I get error.
My Code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
//h=0;
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
//pic = photo;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOptions.inDither = true;
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
Global.img = bitmap;
b.setImageBitmap(bitmap);
String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
//p = path;
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
//pic=file;
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
// h=1;
//imgui = selectedImage;
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ******", picturePath + "");
b.setImageBitmap(thumbnail);
}
}
else
{
finish();
}
}
After follow the tutorial, I have changed my code to
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOptions.inDither = true;
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(f.getAbsolutePath(), opts);
ExifInterface exif = new ExifInterface(f.getAbsolutePath());
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;
Matrix matrix = new Matrix();
matrix.setRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bitmapOptions.outWidth, bitmapOptions.outHeight, matrix, true);
Global.img = bitmap;
b.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
//p = path;
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
setRotate in matrix.setRotate cannot be solved.
I get a red line underneath (bm, 0, 0, bitmapOptions.outWidth, bitmapOptions.outHeight, matrix, true); (cannot resolved method createBitmap )
*********Edit*********
After I import android.graphics.Matrix instead of android.opengl.Matrix, the app crashed.
LogCat error
Process: com.example.project.project, PID: 13045
java.lang.OutOfMemoryError
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:928)
at android.graphics.Bitmap.createBitmap(Bitmap.java:901)
at android.graphics.Bitmap.createBitmap(Bitmap.java:833)
at com.example.project.project.ImageFitScreen.onActivityResult(ImageFitScreen.java:236)
at android.app.Activity.dispatchActivityResult(Activity.java:5643)
This is line 236
Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bitmapOptions.outWidth, bitmapOptions.outHeight, matrix, true);
Change to this Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(),matrix, true);
I guess you imported the wrong Matrix class, you should import android.graphics.Matrix, not android.opengl.Matrix, please double check.
Related
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
}
Hey I have an app that choose an image from the gallery , resizing it and uploading it to ftp server , but I have notice that in some photo's the app flips the image horizontally and upload it backwards, I can't figure out why it is happening (It only happened on some photos and on others not, usually happened on photos taken from my camera)
Here is the code for the resize part:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK&&data!=null) {
selectedImageURI = data.getData();
showUri = data.getData();
imagePath = RealPathUtil.getPath(this,data.getData());
loadedImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
//loadedImage.setImageURI(data.getData());
Glide.with(this).load(data.getData())
.into((ImageView) findViewById(R.id.upload_image1));
ImageView m =(ImageView)findViewById(R.id.remove_image);
m.setFocusable(true);
m.setVisibility(View.VISIBLE);
File file = new File(RealPathUtil.getPath(this,data.getData()));
Bitmap bitmap = decodeFile(file);
ImageResizer(bitmap);
}
}
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
final int REQUIRED_SIZE=200;
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
Bitmap bit1 = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
//Matrix matrix = new Matrix();
//matrix.postRotate(45);
// Bitmap rotatedBitmap = Bitmap.createBitmap(bit1 , 0, 0, bit1 .getWidth(), bit1 .getHeight(), matrix, true);
return bit1;
} catch (FileNotFoundException e) {}
return null;
}
private void ImageResizer(Bitmap bitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Pic");
if(!myDir.exists()) myDir.mkdirs();
String fname = "resized.png";
File file = new File (myDir, fname);
if (file.exists()){
file.delete();
Log.d("exist","replace");
SaveResized(file, bitmap);
} else {
SaveResized(file, bitmap);
Log.d("saved","now");
}
selectedImageURI = Uri.fromFile(file);
imagePath = RealPathUtil.getPath(this,selectedImageURI);
}
private void SaveResized(File file, Bitmap bitmap) {
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
can someone help me and tell me why is it happening?
I am trying to get an image from gallery or take one using camera in android. taking one using camera app works so fine but getting an image from gallery returs a nullpointer when compressing. below shows my code for sellecting from gallery and camera
#Override
protected void onActivityResult(int requestCode, int resultCode, #NonNull Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST1) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
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();
}
image_String = SessionManager.encodeTobase64(thumbnail);
Log.d("bm", image_String.toString());
profile_pic.setImageBitmap(thumbnail);
} else if (requestCode == SELECT_FILE1) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(projection[0]);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
cursor.close();
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;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
image_String = SessionManager.encodeTobase64(bm);
Log.d("bm", image_String.toString());
profile_pic.setImageBitmap(bm);
}
}
}
and here is my mothhod to perform the encoding of the imgage i just got
public static String encodeTobase64(Bitmap img){
Bitmap image = img;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
return imageEncoded;
}
can't figure out the encode method signals an error when compresing the bitmap taken from gallery of device. Please help me out
I have an application with an image view, and when i click on it it opens menu of choosing Take From Gallery/ Open Camera.
after i choose a large image (large size or large scaling) the app crashes.
how can i fix it?
this is the code and logcat:
Select image+onActivityResult:
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose From Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
AddContactActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose From Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imginAdd.setImageBitmap(bitmap);
ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream3);
byteArray = stream3.toByteArray();
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap bitmap = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........",
picturePath + "");
imginAdd.setImageBitmap(bitmap);
ByteArrayOutputStream stream4 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream4);
byteArray = stream4.toByteArray();
}
}
}
Getting the image from another through sql:
(4 lines as one code, i have problem with quoting:)
Blockquote byte[] photo = rs.getBlob(rs
.getColumnIndex(DBHelper.CONTACTS_COLUMN_IMAGE));
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
imginView.setImageBitmap(theImage);
LOGCAT: http://textuploader.com/69on
Simply use this function which will decode your large image too.
private void setPic(final String path) {
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
final BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
bitmap = BitmapFactory.decodeFile(path, bmOptions);
}
Now call this function after retrieve your image path from gallery
setPic(imagepath);
imageView.setImageBitmap(bitmap); // this bitmap object will be declare globally
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