how to upload few images use bitmapFactory? - java

How can I upload images one by one so that the memory is cleared each time after the picture upload has been successfully downloaded and the picture does not disappear from the screen?
Trying to load few images in RecyclerView. Important! Images are loaded from other applications (themes for my app).
Here is the code:
private static final int MAX_SAMPLE = 16;
private static Drawable getDrawableFromResource(Resources themeRes, int resourceID)
{
if (resourceID == 0 || themeRes == null)
return null;
Drawable drawable = null;
Bitmap bitmap = null;
BitmapFactory.Options uniformOptions = new BitmapFactory.Options();
int inputSampleSize = uniformSampleSize;
if (inputSampleSize > MAX_SAMPLE)
inputSampleSize = MAX_SAMPLE;
String resName = getResName(resourceID);
for (int sizeDivider = inputSampleSize; sizeDivider <= MAX_SAMPLE; sizeDivider *= 2)
{
uniformOptions.inSampleSize = sizeDivider;
try
{ bitmap = BitmapFactory.decodeResource(themeRes, resourceID, uniformOptions); }
catch (OutOfMemoryError | Exception e)
{
Log.e(DynamicSettings.TAG_ERROR, "Load drawable: " + (resName != null ? resName : "name not found") + ", sizeDiv: " + sizeDivider);
e.printStackTrace();
continue;
}
try
{
drawable = new BitmapDrawable(bitmap);
return drawable;
}
catch (OutOfMemoryError | Exception e)
{
Log.e(DynamicSettings.TAG_ERROR, "Bad drawable resource file (parsing): " + resName);
e.printStackTrace(); // Out of memory or Null pointer
if (bitmap != null)
bitmap.recycle();
}
}
new BitmapDrawable(getErrorBitmap());
return new BitmapDrawable(getErrorBitmap());
}
If there is not enough memory for all the pictures – they resize using inSampleSize uniformOptions
Here's the error:
If you call bitmap.recycle() or something like that - image dissapear from RecyclerView and throw exception.

Related

Problem with taking screenshots with the media projection android studio

I have this code to make screenshots. In the virtual device of android studio this code works perfectly, but in my own device Samsung(with android 8.0) when I do the apk installer the program only take some screenshots. Example I press the button to take 10 screenshots, but the program only save me 2 and the rest doesn't exist. And now I don't have any idea what's the problem.
#SuppressLint("WrongConstant")
private void screenshot() {
Point size = new Point();
displayy.getSize(size);
mWidth = size.x;
mHeight = size.y;
displayy.getMetrics(metrics);
int mDensity = metrics.densityDpi;
Handler handler=new Handler();
mImageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 2);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
displayyy = mMediaProjection.createVirtualDisplay(DISPLAY_NAME, mWidth, mHeight, mDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, handler);
}
mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
int onImageCount = 0;
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
FileOutputStream fos = null;
Bitmap bitmap = null;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
image = reader.acquireLatestImage();
}
if (image != null) {
Image.Plane[] planes = new Image.Plane[0];
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
planes = image.getPlanes();
}
ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * mWidth;
bitmap = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy_HH:mm:ss");
String formattedDate = df.format(Calendar.getInstance().getTime()).trim();
String finalDate = formattedDate.replace(":", "-");
String imgName = "/imagen"+ "_" + finalDate + ".jpg";
String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/example";
File dir = new File(dirPath);
if(!dir.exists()){
dir.mkdirs();
}
String mPath = dirPath + imgName;
File imageFile = new File(mPath);
fos = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Log.e(TAG, "captured image: " );
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bitmap != null) {
bitmap.recycle();
}
if (image != null) {
image.close();
}
}
}
}, handler);
mMediaProjection.stop();
mMediaProjection=null;
}
I don't know if you've already solved your problem, but here's my solution:
The method receives 4 parameters and the last one is the number of photos
enter code hereImageReader.newInstance(width: Int, height: Int, format: Int, maxImages: Int)
If you look good you are sending it in the last parameter the number of photos 2
enter code hereImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 2);
enter link description here

Camera Intent doesn't save image to gallery

I'm a newbie android developer.Now I found an error when I compiled my camera application.
Actually the camera intent is working properly and the image taken can be shown on ImageView, but it isn't saved automatically to my phone gallery. After research, it took 3 days after picture taken to get saved in the image gallery.
I already tried some different methods of camera intent, but until now I have no significant results. Any help will be so much appreciated, thank you.
my target SDK is 27 API, I already made an XML file for provider_paths and describe it in my manifests.
here is my camera intent:
public static final int REQUEST_CAMERA = 100;
Uri fileUri;
public final int SELECT_FILE = 11;
int bitmap_size = 40; // image quality 1 - 100;
int max_resolution_image = 800;
private void openCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
public Uri getOutputMediaFileUri() {
return FileProvider.getUriForFile(LaporActivity.this,
BuildConfig.APPLICATION_ID + ".fileprovider",
getOutputMediaFile());
}
private static File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "KSD");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e("Monitoring", "Oops! Failed create Monitoring directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_KSD_" + timeStamp + ".jpg");
return mediaFile;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("onActivityResult", "requestCode " + requestCode + ", resultCode " + resultCode);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
try {
Log.e("CAMERA", fileUri.getPath());
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri));
setToImageView(getResizedBitmap(bitmap, max_resolution_image));
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE && data != null && data.getData() != null) {
try {
// choose picture from Gallery
bitmap = MediaStore.Images.Media.getBitmap(LaporActivity.this.getContentResolver(), data.getData());
setToImageView(getResizedBitmap(bitmap, max_resolution_image));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void setToImageView(Bitmap bmp) {
//compress image
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, bytes);
decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray()));
//shows chosen picture from gallery to imageview
fotoCaptured.setImageBitmap(decoded);
}
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
I expected the picture to get saved automatically to my gallery so I can continue to upload-process method using Retrofit, but the actual is when I clicked upload-button, the toast shows "IMGxxxxx No such file/directory" because the image path is not properly saved.
Your file exist in memory but not on disk. Create the file before returning the object
private static File getOutputMediaFile() {
...
...
//create file on disk
if(!mediaFile.exists()) mediaFile.createNewFile();
return mediaFile;
}

Image Orientation - Android

I have been struggling with this bug on and off for the last month or so. Everytime that I think I have fixed it it seems to come back in some form.
It is the old Android "Image Rotated 90 degrees" bug. I have read countless Posts on here (StackOverFlow) aswell as tried numerous methods but just cannot seem to fix it.
I am still getting images that are rotated incorrectly.
In my application a user chooses his/her profile Picture, which is then set to an ImageView. The image is chosen from the Phones Gallery
Two days ago I implemented the Following Code, this worked for all the images I tested it with on my Phone. However when one of my Beta testers tried it, his images were once again rotated. He sent me the images for testing but they were displaying fine on my Phone. Hence why I am getting more and more frustrated.
This is the method I am using to get the Images orientation:
// Gets an Images Orientation
public static int getOrientationEXIF(Context context, Uri uri) {
int orientation = 0;
try {
ExifInterface exif = new ExifInterface(uri.getPath());
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
return orientation;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
return orientation;
}
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
I then get a rotated Bitmap using this Method:
// Rotate a Bitmap
public static Bitmap rotate(float rotationValue, String filePath) {
Bitmap original= BitmapFactory.decodeFile(filePath);
int width = original.getWidth();
int height = original.getHeight();
Matrix matrix = new Matrix();
matrix.postRotate(rotationValue);
Bitmap rotated = Bitmap.createBitmap(original, 0, 0, width, height, matrix, true);
return rotated;
}
I am just not sure what to do anymore.
I would really like it if someone could help me figure this out
Thank you in advance
UPDATE
I just saw the following line of Code in my Log after implementing the suggested Methods:
JHEAD can't open 'file:/external/images/media/3885'
I am not sure what this means
UPDATE #2
I think I may have fixed the problem, I got the proper image path for the file.
You need to account for all orientations not just 90 or 180. I am using this
File curFile = new File("path-to-file"); // ... This is an image file from my device.
Bitmap rotatedBitmap;
try {
ExifInterface exif = new ExifInterface(curFile.getPath());
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {matrix.preRotate(rotationInDegrees);}
rotatedBitmap = Bitmap.createBitmap(bitmap,0,0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}catch(IOException ex){
Log.e(TAG, "Failed to get Exif data", ex);
}
and:
/**
* Gets the Amount of Degress of rotation using the exif integer to determine how much
* we should rotate the image.
* #param exifOrientation - the Exif data for Image Orientation
* #return - how much to rotate in degress
*/
private static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; }
else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; }
else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; }
return 0;
}
This problem really sucks ! I notice this is an issue when choosing photos rather than taking them. I found the answer buried in the code for this cropping lib which seemed to always display things correctly https://github.com/jdamcd/android-crop while cropping (despite it sometimes returning things with wrong orientation afterwards). Anyways, first start off by choosing the photo the way I choose in this answer: Pick image from fragment always return resultcode 0 in some devices
Next do this where you need to:
private void setRotationVariables(Uri uri)
{
m_rotationInDegrees = ImageOrientationUtil.getExifRotation(ImageOrientationUtil
.getFromMediaUri(
this,
getContentResolver(),
uri));
}
Here is the class:
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import java.io.Closeable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageOrientationUtil
{
private static final String SCHEME_FILE = "file";
private static final String SCHEME_CONTENT = "content";
public static void closeSilently(#Nullable Closeable c) {
if (c == null) return;
try {
c.close();
} catch (Throwable t) {
// Do nothing
}
}
public static int getExifRotation(File imageFile) {
if (imageFile == null) return 0;
try {
ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
// We only recognize a subset of orientation tag values
switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)) {
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270;
default:
return ExifInterface.ORIENTATION_UNDEFINED;
}
} catch (IOException e) {
// Log.e("Error getting Exif data", e);
return 0;
}
}
#Nullable
public static File getFromMediaUri(Context context, ContentResolver resolver, Uri uri) {
if (uri == null) return null;
if (SCHEME_FILE.equals(uri.getScheme())) {
return new File(uri.getPath());
} else if (SCHEME_CONTENT.equals(uri.getScheme())) {
final String[] filePathColumn = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME };
Cursor cursor = null;
try {
cursor = resolver.query(uri, filePathColumn, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
final int columnIndex = (uri.toString().startsWith("content://com.google.android.gallery3d")) ?
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME) :
cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
// Picasa images on API 13+
if (columnIndex != -1) {
String filePath = cursor.getString(columnIndex);
if (!TextUtils.isEmpty(filePath)) {
return new File(filePath);
}
}
}
} catch (IllegalArgumentException e) {
// Google Drive images
return getFromMediaUriPfd(context, resolver, uri);
} catch (SecurityException ignored) {
// Nothing we can do
} finally {
if (cursor != null) cursor.close();
}
}
return null;
}
private static String getTempFilename(Context context) throws IOException {
File outputDir = context.getCacheDir();
File outputFile = File.createTempFile("image", "tmp", outputDir);
return outputFile.getAbsolutePath();
}
#Nullable
private static File getFromMediaUriPfd(Context context, ContentResolver resolver, Uri uri) {
if (uri == null) return null;
FileInputStream input = null;
FileOutputStream output = null;
try {
ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
FileDescriptor fd = pfd.getFileDescriptor();
input = new FileInputStream(fd);
String tempFilename = getTempFilename(context);
output = new FileOutputStream(tempFilename);
int read;
byte[] bytes = new byte[4096];
while ((read = input.read(bytes)) != -1) {
output.write(bytes, 0, read);
}
return new File(tempFilename);
} catch (IOException ignored) {
// Nothing we can do
} finally {
closeSilently(input);
closeSilently(output);
}
return null;
}
}
mochilogic answer is very good but his comment is also correct:
sorry, " do this where you need to " is so vague.."
I cannot add all of this in comment to mochilogic answer so I will write this here: If you dont like touse it in setRotationVariables(data.getData) - this is another way to use the class ImageOrientationUtil from his answer and this method:
private void setRotationVariables(Uri uri)
{
m_rotationInDegrees = ImageOrientationUtil.getExifRotation
(ImageOrientationUtil.getFromMediaUri(
this,
getContentResolver(),
uri));
}
You can send Uri from the galery to this method make it return the correct rotation in degrees by memebr as he does or by value as I did:
private static int setRotationVariables(Uri uri) {
int rotationInDegrees = ImageOrientationUtil.getExifRotation(ImageOrientationUtil
.getFileFromMediaUri(
appCtx,
appCtx.getContentResolver(),
uri));
Log.d(TAG, "setRotationVariables:" + "according to original Image Uri Exif details we need to rotate in "+rotationInDegrees + " Degrees");
return rotationInDegrees;
}
and then on the calling function after you scale your Uri to bitmap you can create bitmap using this rotationInDegrees with a matrix.
you can see it in my code here in this method I take Uri and scale it and rotate it and then returns it as bitmap.
but first - basicaly this is what you need:
int rotationDegree = setRotationVariables(uri);
if (rotationDegree > 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotationDegree);
Log.w(TAG, "recreating bitmap with rotation of " + rotationDegree + " degrees" );
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
This is the full method code if anyones need it..
public static Bitmap getScaledBitmapFromUri(Uri uri) throws FileNotFoundException, IOException {
final int TRY_SCALE_TO_THIS_SIZE = 1024;
Log.d(TAG, "getScaledBitmapFromUri:: calling setRotationVariables() to figure rotationDegree");
int rotationDegree = setRotationVariables(uri);
Context ctx = MessagingApp.getContext();
InputStream input = ctx.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither = true;//optional
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
if ( (onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1) )
return null;
int BiggestOriginalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;
//we will add 1 to Math.round (BiggestOriginalSize / (double)TRY_SCALE_TO_THIS_SIZE) in order to harden the scaling(we need smaller images for this project!)
double ratio = (BiggestOriginalSize > TRY_SCALE_TO_THIS_SIZE) ? (1 + Math.round(BiggestOriginalSize / (double) TRY_SCALE_TO_THIS_SIZE)) : 1.0;
Log.w(TAG, "getScaledBitmapFromUri:: originalSize: " + BiggestOriginalSize + "PX, TRY_SCALE_TO_THIS_SIZE (if original is bigger):" + TRY_SCALE_TO_THIS_SIZE +"PX");
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio); //this one will give abstract results (sometimes bigger then TRY_SCALE_TO_THIS_SIZE)
Log.w(TAG, format("bitmapOptions.inSampleSize: " + bitmapOptions.inSampleSize));
bitmapOptions.inJustDecodeBounds = false; //check this out!!! maybe delete?
bitmapOptions.inDither = true;//optional
bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
//bitmapOptions.rogetrotationInDegrees
input = ctx.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
//bitmap = findExactInSampleSize(onlyBoundsOptions, TRY_SCALE_TO_THIS_SIZE, bitmap); // this one will never give bigger length then TRY_SCALE_TO_THIS_SIZE
if (rotationDegree > 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotationDegree);
Log.w(TAG, "recreating bitmap with rotation of " + rotationDegree + " degrees" );
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
Log.w(TAG, "after decodeStream : bitmap.getWidth(): " + bitmap.getWidth() + "PX, bitmap.getHeight(): " + bitmap.getHeight() +"PX.");
input.close();
return bitmap;
}

App says Image Downloaded Successfully but no image shows up in gallery

The app gets the image from the given URL and displays the image and on clicking the download button, it says that the image has been downloaded successfully but there is no image in the gallery. Can someone tell me how I can fix this?
This is my Image View and Download activity. I have also added proper permissions to the Android Manifest.
private Button btnImageDownload;
private ProgressDialog pd;
private ImageView viewDownloadImage;
private Images imageId;
private File folderName;
private String imageName;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
if (pd != null) {
pd.dismiss();
}
Utils.showNetworkAlert(ImageViewAndDownload.this);
} else if (msg.what == 2) {
if (pd != null) {
pd.dismiss();
}
Utils.displayMessage("Image downloade succesfully",
ImageViewAndDownload.this);
// Media scaning
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
} else if (msg.what == 3) {
if (pd != null) {
pd.dismiss();
}
Utils.displayMessage("Image already downloaded ",
ImageViewAndDownload.this);
} else if (msg.what == 4) {
if (pd != null) {
pd.dismiss();
}
displayImageFromUrl((Bitmap) msg.obj);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagedisplay);
viewDownloadImage = (ImageView) findViewById(R.id.viewImage);
btnImageDownload = (Button) findViewById(R.id.btnImageDownload);
imageId = new Images();
imageName = imageId.getImageId();
LoadImageFromWeb(Constant.IMAGE_BASE_URL + File.separator + imageName);
btnImageDownload.setOnClickListener(this);
}
public void onClick(View v) {
if (v == btnImageDownload) {
pd = ProgressDialog.show(ImageViewAndDownload.this, "",
"Downloading Image....", true, false);
new Thread(new Runnable() {
public void run() {
try {
String imageUrl = Constant.IMAGE_BASE_URL
+ File.separator + imageName;
String isDownloded = downloadImage(imageUrl, imageName);
if (isDownloded.equalsIgnoreCase("complete")) {
handler.sendEmptyMessage(2);
} else if (isDownloded.equalsIgnoreCase("")) {
handler.sendEmptyMessage(3);
} else {
handler.sendEmptyMessage(1);
}
} catch (Exception e) {
e.printStackTrace();
handler.sendEmptyMessage(1);
}
}
}).start();
}
}
// set display image to Imageview
public void displayImageFromUrl(Bitmap obj) {
viewDownloadImage.setImageBitmap(obj);
}
// image display from the webview
private void LoadImageFromWeb(final String url1) {
pd = ProgressDialog.show(ImageViewAndDownload.this, "",
"Loading Image....", true, false);
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
InputStream is = connection.getInputStream();
Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
if (options.outWidth > 3000 || options.outHeight > 2000) {
options.inSampleSize = 4;
} else if (options.outWidth > 2000
|| options.outHeight > 1500) {
options.inSampleSize = 3;
} else if (options.outWidth > 1000
|| options.outHeight > 1000) {
options.inSampleSize = 2;
}
// Do the actual decoding
options.inJustDecodeBounds = false;
is.close();
is = getHTTPConnectionInputStream(url1);
Bitmap myBitmap = BitmapFactory.decodeStream(is, null,
options);
is.close();
if (myBitmap != null) {
Message msg = new Message();
msg.obj = myBitmap;
msg.what = 4;
handler.sendMessage(msg);
} else {
handler.sendEmptyMessage(1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public InputStream getHTTPConnectionInputStream(String url1) {
URL url;
InputStream is = null;
try {
url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
is = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
// image download code
public String downloadImage(String imageDownloadUrl, String imageName) {
// create directory in SDCARD
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
folderName = new File(Constant.STORE_IN_FOLDER);
else
folderName = getFilesDir();
if (!folderName.exists())
folderName.mkdirs();
String response = "";
// create file name and file.
File storeImageInSDCard = new File(folderName + File.separator
+ imageName);
if (!(storeImageInSDCard.exists() && storeImageInSDCard.length() > 0)) {
// start download image
response = downloadFile(imageDownloadUrl, imageName,
folderName.toString());
}
return response;
}
// start download image
public String downloadFile(final String url, final String name,
String foldername) {
File file;
FileOutputStream os = null;
Bitmap myBitmap;
try {
URL url1 = new URL(url.replaceAll(" ", "%20"));
System.out.println("Image url :::" + url1);
HttpURLConnection urlConnection = (HttpURLConnection) url1
.openConnection();
urlConnection.setDoOutput(false);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// here create a file which define folder name and image name with
// extension.
file = new File(foldername, name + ".jpg");
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
os = new FileOutputStream(file);
while ((bufferLength = inputStream.read(buffer)) > 0) {
os.write(buffer, 0, bufferLength);
}
os.flush();
os.close();
// if image size is too large we can scale image than download.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
myBitmap = BitmapFactory
.decodeFile(file.getAbsolutePath(), options);
if (options.outWidth > 3000 || options.outHeight > 2000) {
options.inSampleSize = 4;
} else if (options.outWidth > 2000 || options.outHeight > 1500) {
options.inSampleSize = 3;
} else if (options.outWidth > 1000 || options.outHeight > 1000) {
options.inSampleSize = 2;
}
options.inJustDecodeBounds = false;
myBitmap = BitmapFactory
.decodeFile(file.getAbsolutePath(), options);
os = new FileOutputStream(file);
myBitmap.compress(CompressFormat.JPEG, 90, os);
os.flush();
os.close();
myBitmap.recycle();
return "complete";
} catch (SQLException e) {
e.printStackTrace();
return "error";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
}
try this,
After saving the Image you have to use this
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
you have to send a broadcast to System ,changes to reflect in the Gallery , so that you image will be shown in the gallery , if not , you have to restart Device for check the downloaded images..
hope it helps you..
I think you have to use Aquery for image download it is very Useful for image download from net.
Here the link for Aquery

GestureImagView in android

I'm using a GestureImageView Project that I've got from Github, I have several images in my drawable folder : page1.jpg, page2.jpg, page3.jpg,.........page30.jpg. I have a variable called pagenumber, when I click on a button this variable will increment, alson I want to load the image in the GestureImageView. Here is my code in the Main Class :
pagenumber++;
GestureImageView view1 = (GestureImageView) findViewById(R.id.image);
String uriPath = "android.resource://"+getPackageName()+"/drawable/page"+String.valueOf(pagenumber);
Uri uri = Uri.parse(uriPath);
view1 .setImageURI(uri);
In the GestureImageView.java the code is :
#Override
public void setImageURI(Uri mUri) {
if ("content".equals(mUri.getScheme())) {
try {
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Cursor cur = getContext().getContentResolver().query(mUri, orientationColumn, null, null, null);
if (cur != null && cur.moveToFirst()) {
imageOrientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
}
InputStream in = null;
try {
in = getContext().getContentResolver().openInputStream(mUri);
Bitmap bmp = BitmapFactory.decodeStream(in);
if(imageOrientation != 0) {
Matrix m = new Matrix();
m.postRotate(imageOrientation);
Bitmap rotated = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), m, true);
bmp.recycle();
setImageDrawable(new BitmapDrawable(getResources(), rotated));
}
else {
setImageDrawable(new BitmapDrawable(getResources(), bmp));
}
}
finally {
if(in != null) {
in.close();
}
if(cur != null) {
cur.close();
}
}
}
catch (Exception e) {
Log.w("GestureImageView", "Unable to open content: " + mUri, e);
}
}
else {
setImageDrawable(Drawable.createFromPath(mUri.toString()));
}
if (drawable == null) {
Log.e("GestureImageView", "resolveUri failed on bad bitmap uri: " + mUri);
// Don't try again.
mUri = null;
}
}
Well I'm having an empty image in the GestureImageView, it's not loading. The logcat says Unable to decode stream : java.io.FileNotFoundException: /android.resource:/com.example.tests/drawable/page3 : open failed : ENOENT (No such file or directory). I also tried to add the .png extension but I had the same result.
Please note that when I use an imageview instead of GestureImageView it works
Any help please ?

Categories

Resources