Image is not showing in gallery - java

I am getting an image from image view and convert it into bitmap and after that i have save it in a directory. Image is saved successfully in my directory but is is not showing in galley.
I have some other images in same directory that is saved after taking picture from camera are visible. I just save image from an ImageView and store it into a directory and in next screen i just want to use the saved image to fetch the information.
textToImage() method is used to create an encoded image.
Bitmap TextToImageEncode(String Value) throws WriterException {
BitMatrix bitMatrix;
try {
bitMatrix = new MultiFormatWriter().encode(
Value,
BarcodeFormat.DATA_MATRIX.QR_CODE,
QRcodeWidth, QRcodeWidth, null
);
} catch (IllegalArgumentException Illegalargumentexception) {
return null;
}
int bitMatrixWidth = bitMatrix.getWidth();
int bitMatrixHeight = bitMatrix.getHeight();
int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];
for (int y = 0; y < bitMatrixHeight; y++) {
int offset = y * bitMatrixWidth;
for (int x = 0; x < bitMatrixWidth; x++) {
pixels[offset + x] = bitMatrix.get(x, y) ?
getResources().getColor(R.color.QRCodeBlackColor) : getResources().getColor(R.color.QRCodeWhiteColor);
}
}
Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);
bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight);
if (bitmap != null)
saveImageToSdCard(bitmap);
} else {
Log.e("Test data image or not", "No bitmap given");
}
return bitmap;
}
"I have use this method to save the image in my directory"
public void saveImageToSdCard(Bitmap bitmap1) {
File sdCard = Environment.getExternalStorageDirectory();
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
if (sdCard != null) {
> Create the directory here with path
File directory = new File(ExternalStorageDirectoryPath+"/My App");
if (directory.exists()) {
directory.delete();
Log.e("it run", "directory is exists");
}
directory.mkdirs();
String strImageName = File.separator + "IMG_" + timeStamp + ".jpg";
File file = new File(directory, strImageName);
// strFinalImage = file.getAbsolutePath();
// Log.e(TAG + "strFinalImage22", strFinalImage + "");
> here we just scan the media
MediaScannerConnection.scanFile(getActivity(),
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.e("ExternalStorage", "Scanned " + path + ":");
Log.e("ExternalStorage", "-> uri=" + uri);
}
});
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
fileOutputStream.write(bytes.toByteArray());
fileOutputStream.flush();
fileOutputStream.close();
// Toast.makeText(MainActivity.this, "Saved", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
} else {
Toast.makeText(getActivity(), "Sd card mount", Toast.LENGTH_SHORT).show();
}
}

Related

How to detect uris from moved files

Anyone knows how to detect uris from moved files programmatically in Java/Android?When I start the app I detect all images in my phone (with their uris, path....), if I move the images with a media manager, next time I start the app I can get the whole uris again, with the new path. But, if I move these images programmatically (copying the image and deleting the image from the original path) next time I start the app the uris will be the previous path a not the new one. I'm trying to fix deleting the app cache, but doesn't work. Anyone knows what can be happen?
I tried to move the files with two functions and I have same problem:
public static void moveFile(ArrayList<ImagesData> images) throws IOException {
for (int i = 0; i < images.size(); i++) {
File file_Source = new File(images.get(i).imagePath);
File file_Destination = new File(Environment.getExternalStorageDirectory() + "/PrivateGallery/" + new File(images.get(i).imagePath).getName());
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(file_Source).getChannel();
destination = new FileOutputStream(file_Destination).getChannel();
Log.i(TAG, "Source " + source + " destination " + destination);
long count = 0;
long size = source.size();
while((count += destination.transferFrom(source, count, size-count)) < size);
//destination.transferFrom(source, 0, source.size());
file_Source.delete();
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
}
public void changeToNewPath(ArrayList<ImagesData> images) {
String outputPath = Environment.getExternalStorageDirectory() + "/PrivateGallery/";
//TODO COMPROBAR SI EXISTE YA UN ARCHIVO CON SU NOMBRE
InputStream in = null;
OutputStream out = null;
for(int i = 0; i < images.size(); i++) {
try { //TODO revisar lod el cambio de directorio
//create output directory if it doesn't exist
//File dir = new File(outputPath);
File f = new File(images.get(i).imagePath);
String a = f.getName();
Log.e(TAG, a);
in = new FileInputStream(images.get(i).imagePath);
out = new FileOutputStream(outputPath + new File(images.get(i).imagePath).getName());
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
// write the output file
out.flush();
out.close();
out = null;
// delete the original file
new File(images.get(i).imagePath).delete();
} catch (FileNotFoundException fnfe1) {
Log.e("tag", fnfe1.getMessage());
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
}

multi-pag tif to several jpeg files (java)

Hello I was able to convert a tif file to jpeg with the following code that I got from
https://stackoverflow.com/questions/15429011/how-to-convert-tiff-to-jpeg-png-in-java#=
String inPath = "./tifTest/113873996.002.tif";
String otPath = "./tifTest/113873996.002-0.jpeg";
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(inPath), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(new FileOutputStream(otPath), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(TifToJpeg.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TifToJpeg.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This only works with one-page tif file, and when I use it with a multi-page tif, it only saves the first page.
How can I modified this to save a mymultipagetif.tif into:
mymultipagetif-0.jpeg
mymultipagetif-1.jpeg
mymultipagetif-2.jpeg
Thanks!
This will takes a multi-page TIFF file (in the SeekableStream), extract the pages in the pages array ("1", "3", "4" for example) and write them into a single multi-page tiff into the file outTIffFileName. Modify as desired.
private String _ExtractListOfPages (SeekableStream ss, String outTiffFileName, String[] pages){
// pageNums is a String array of 0-based page numbers.
try {
TIFFDirectory td = new TIFFDirectory(ss, 0);
if (debugOn) {
System.out.println("Directory has " + Integer.toString(td.getNumEntries()) + " entries");
System.out.println("Getting TIFFFields");
System.out.println("X resolution = " + Float.toString(td.getFieldAsFloat(TIFFImageDecoder.TIFF_X_RESOLUTION)));
System.out.println("Y resolution = " + Float.toString(td.getFieldAsFloat(TIFFImageDecoder.TIFF_Y_RESOLUTION)));
System.out.println("Resolution unit = " + Long.toString(td.getFieldAsLong(TIFFImageDecoder.TIFF_RESOLUTION_UNIT)));
}
ImageDecoder decodedImage = ImageCodec.createImageDecoder("tiff", ss, null);
int count = decodedImage.getNumPages();
if (debugOn) { System.out.println("Input image has " + count + " page(s)"); }
TIFFEncodeParam param = new TIFFEncodeParam();
TIFFField tf = td.getField(259); // Compression as specified in the input file
param.setCompression(tf.getAsInt(0)); // Set the compression of the output to be the same.
param.setLittleEndian(false); // Intel
param.setExtraFields(td.getFields());
FileOutputStream fOut = new FileOutputStream(outTiffFileName);
Vector<RenderedImage> vector = new Vector<RenderedImage>();
RenderedImage page0 = decodedImage.decodeAsRenderedImage(Integer.parseInt(pages[0]));
BufferedImage img0 = new BufferedImage(page0.getColorModel(), (WritableRaster)page0.getData(), false, null);
int pgNum;
// Adding the extra pages starts with the second one on the list.
for (int i = 1; i < pages.length; i++ ) {
pgNum = Integer.parseInt(pages[i]);
if (debugOn) { System.out.println ("Page number " + pgNum); }
RenderedImage page = decodedImage.decodeAsRenderedImage(pgNum);
if (debugOn) { System.out.println ("Page is " + Integer.toString(page.getWidth()) + " pixels wide and "+ Integer.toString(page.getHeight()) + " pixels high."); }
if (debugOn) { System.out.println("Adding page " + pages[i] + " to vector"); }
vector.add(page);
}
param.setExtraImages(vector.iterator());
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", fOut, param);
if (debugOn) { System.out.println("Encoding page " + pages[0]); }
encoder.encode(decodedImage.decodeAsRenderedImage(Integer.parseInt(pages[0])));
fOut.close();
} catch (Exception e) {
System.out.println(e.toString());
return("Not OK " + e.getMessage());
}
return ("OK");
}

Creation of GIF is taking so long time in Android

I am creating a app which burst capture images and create a GIF as output. My problem is creation of GIF from the image sequence is taking so long time, whether the resolution of images are 320x240. I am using AnimatedGifEncoder class for GIF encoding. as follow this link.
My code for creation of GIF is as following
private void saveGifImage() {
FileOutputStream outStream =
String fileName = "test.gif";
try {
File file = new File(Environment.getExternalStorageDirectory() + "/gif_convertor/sample/");
if (!file.exists())
file.mkdirs();
File file1 = new File(file + File.separator +
if (file1.exists()) {
} else {
try {
// file1.mkdirs();
file1.createNewFile();
} catch (Exception e) {
}
}
outStream = new FileOutputStream(file1);
Log.d("Location", file1.getPath().toString());
outStream.write(generateGIF());
outStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
DialogUtils.stopProgressDisplay();
}
}
private byte[] generateGIF() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
encoder.delay = 33; // 50 means 0.5 seconds ( 100 value is equivalent to 1 seconds)
encoder.repeat = 0; // 0 means repeat forever, other n positive integer means n times repeat , -1 means no repeat
encoder.sizeSet = true; // resize allowed with true flag
encoder.width = 320;
encoder.height = 240;
File tempDir = new File(getActivity().getExternalFilesDir(null), "temp");
if (tempDir.exists()) {
for (File file : tempDir.listFiles()) {
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
encoder.addFrame(bitmap);
}
}
encoder.finish();
return bos.toByteArray();
}

picture rotated 90 degrees when copy the picture from URI to file

I was trying to copy a picture from URI to a file path. Then I read the picture from the path, but the picture I got was rotated 90 degrees down. Below is my function. Anybody can help on this?
public boolean copyPicture(Context context, Uri source, String dest) {
boolean result = false;
int bytesum = 0;
int byteread = 0;
File destFile = new File(dest);
String scheme = source.getScheme();
if (ContentResolver.SCHEME_CONTENT.equals(scheme)
|| ContentResolver.SCHEME_FILE.equals(scheme)) {
InputStream inStream = null;
try {
inStream = context.getContentResolver().openInputStream(source);
if (!destFile.exists()) {
result = destFile.createNewFile();
}
if (result) {
FileOutputStream fs = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.flush();
fs.close();
}
} catch (Exception e) {
e.printStackTrace();
result = false;
}
}
return result;
}
EXIF INTERFACE is the answer. It allows you to read specified attributes from a image file.
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
try {
ExifInterface exif = new ExifInterface(path);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270;
}
Matrix mat = new Matrix();
mat.postRotate(angle);
Bitmap correctBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mat, true);
bitmap=correctBmp;
}
catch(Exception e){
}

Why i cannot show my byte[] image after converting it from bitmap?

I'm trying to write a method that accepts an image(Bitmap) and returns a byte[] array. finally, I try to write this byte[] array to a folder so I can see the difference, but my byte[] arraycan not displayed, and in addition, it is not scaled down! This is my method:
private byte[] changeSize(Bitmap image) {
byte[] picture;
int width = image.getWidth();
int height = image.getHeight();
int newHeight = 0, newWidth = 0;
if (width > 250 || height > 250) {
if (width > height) { //landscape-mode
newHeight = 200;
newWidth = (newHeight * width) / height;
} else { //portrait-mode
newWidth = 200;
newHeight = (newWidth * height) / width;
}
} else {
Toast.makeText(this, "Something wrong!", Toast.LENGTH_LONG).show();
}
Bitmap sizeChanged = Bitmap.createScaledBitmap(image, newWidth, newHeight, true);
//Convert bitmap to a byte array
int bytes = sizeChanged.getByteCount();
ByteBuffer bb = ByteBuffer.allocate(bytes);
sizeChanged.copyPixelsFromBuffer(bb);
picture = bb.array();
//Write to a hd
picturePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String fileName = edFile.getText().toString() + "_downscaled" + ".jpg";
File file = new File(picturePath, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(picture);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
I tried several hours to get my byte[] array visible, but I could simply not do this. Any help or hints to show me where I derail is/are very appreciated.
This was working for me
public static Bitmap byteArraytoBitmap(byte[] bytes) {
return (BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
}
public static byte[] bitmaptoByteArray(Bitmap bmp) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); //PNG format is lossless and will ignore the quality setting!
byte[] byteArray = stream.toByteArray();
return byteArray;
}
public static Bitmap bitmapFromFile(File file) {
//returns null if could not decode
return BitmapFactory.decodeFile(file.getPath());
}
public static boolean saveImage(Bitmap image, String filePath) {
LogInfo(TAG, "Saving image to: " + filePath);
File file = new File(filePath);
File fileDirectory = new File(file.getParent());
LogInfo(TAG, fileDirectory.getPath());
if (!fileDirectory.exists()) {
if (!fileDirectory.mkdirs()) {
Log.e(TAG, "ERROR CREATING DIRECTORIES");
return false;
}
}
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bitmaptoByteArray(image));
fo.flush();
fo.close();
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}

Categories