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?
Related
This question already has answers here:
How to use "Share image using" sharing Intent to share images in android?
(17 answers)
Closed 2 years ago.
I am making QR code generator
So far I made a generator button and save button.
It works fine.
I am trying to work on the sharing button.
It takes a few days to figure out as a beginner and still I cannot make it work.
At this code, if I click share, then the app closes.
/**Barcode share*/
findViewById(R.id.share_barcode).setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(),R.id.qr_image);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
});
I guessed the problem was path.
I use savepath to save qr code image. And then maybe it conflicts with String path
So I tried String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";;
It's not working. So maybe it's different problem and I don't know how to fix it.
Could you show me how to fix?
MainActivity
public class MainActivity extends AppCompatActivity {
private String inputValue;
private String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
private Bitmap bitmap;
private QRGEncoder qrgEncoder;
private ImageView qrImage;
private EditText edtValue;
private AppCompatActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qrImage = findViewById(R.id.qr_image);
edtValue = findViewById(R.id.edt_value);
activity = this;
/**Barcode Generator*/
findViewById(R.id.generate_barcode).setOnClickListener(view -> {
inputValue = edtValue.getText().toString().trim();
if (inputValue.length() > 0) {
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
qrgEncoder = new QRGEncoder(
inputValue, null,
QRGContents.Type.TEXT,
smallerDimension);
qrgEncoder.setColorBlack(Color.BLACK);
qrgEncoder.setColorWhite(Color.WHITE);
try {
bitmap = qrgEncoder.getBitmap();
qrImage.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else {
edtValue.setError(getResources().getString(R.string.value_required));
}
});
/**Barcode save*/
findViewById(R.id.save_barcode).setOnClickListener(v -> {
String filename = edtValue.getText().toString().trim();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
try {
ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename + ".jpg");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Objects.requireNonNull(fos).close();
Toast toast= Toast.makeText(getApplicationContext(),
"Image Saved. Check your gallery.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
edtValue.setText(null);
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
boolean save = new QRGSaver().save(savePath, filename, bitmap, QRGContents.ImageType.IMAGE_JPEG);
String result = save ? "Image Saved. Check your gallery." : "Image Not Saved";
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
edtValue.setText(null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
}
});
/**Barcode share*/
findViewById(R.id.share_barcode).setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(),R.id.qr_image);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
});
}
}
I think you can solve this by:
Saving the bitmap in a file.
Then sharing the URI of that file in the intent.
In the code below, I am saving the image at the app level directory, you can choose your own and the code is written in kotlin.
Note: If you are using an app-level directory for saving the image then you must use the file provide to get the URI else it may result in FileUriExposedException
try {
val file = File(getExternalFilesDir(null),System.currentTimeMillis().toString() + ".png")
file.createNewFile()
val b = imageView.drawable.toBitmap()
FileOutputStream(file).use { out ->
b.compress(Bitmap.CompressFormat.PNG, 100, out)
}
val share = Intent(Intent.ACTION_SEND)
share.type = "image/jpeg"
val photoURI = FileProvider.getUriForFile(this, applicationContext.packageName.toString() + ".provider", file)
share.putExtra(Intent.EXTRA_STREAM, photoURI)
startActivity(Intent.createChooser(share, "Share Image"))
Toast.makeText(this, "Completed!!", Toast.LENGTH_SHORT).show()
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
}
In JAVA:
public void shareImage(Activity activity, ImageView imageView) {
try {
File file = new File(activity.getExternalFilesDir(null), System.currentTimeMillis() + ".png");
file.createNewFile();
Bitmap bitmap = drawableToBitmap(imageView.getDrawable());
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
Intent share = new Intent("android.intent.action.SEND");
share.setType("image/jpeg");
Uri photoURI = FileProvider.getUriForFile(activity,activity.getPackageName(), file);
share.putExtra("android.intent.extra.STREAM", photoURI);
activity.startActivity(Intent.createChooser(share, "Share Image"));
} catch (Exception var14) {
}
}
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
I currently successfully uploaded an image inside my mobile app to the server.
I am trying to figure out how to resize the image and potentially created a thumbnail before I send this to the server. I have tried many methods I found online but none work.
Below is my code so far.
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
public void uploadMultipart() {
SessionHandler mySession = new SessionHandler(this);
User user = mySession.getUserDetails();
String title = editText.getText().toString().trim();
String path = getPath(filePath);
String studentid = user.studentid;
String email = user.email;
String firstname = user.firstname;
//Toast.makeText(this, firstname, Toast.LENGTH_SHORT).show();
try {
String uploadId = UUID.randomUUID().toString();
uploadReceiver.setDelegate(this);
uploadReceiver.setUploadID(uploadId);
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image")
.addParameter("title", title)
.addParameter("studentid", studentid)
.addParameter("firstname", firstname)
.addParameter("email", email)
//.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload();
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
To compress your image write this method on your activity
public void compressImage(String filePath) {
try {
OutputStream outStream = null;
Log.i("filePath",filePath);
outStream = new FileOutputStream(filePath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(filePath ,bmOptions);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
outStream.flush();
outStream.close();
Log.i("file path compress", filePath);
} catch (Exception e) {
Log.i("exception", e.toString());
}
}
and call it in your on activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TAKE_PHOTO){ //your request code
filePath = data.getData();
try {
compressImage(filePath);
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can compress your image as much as you want on the compressImage method.
public Bitmap resizeBitmap(Bitmap bitmap, int newWidth, int newHeight) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(
bitmap, 0, 0, width, height, matrix, false);
bitmap.recycle();
return resizedBitmap;
}
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
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.
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