Generate image byte from image Path - android

I have an android application i'm developing but i have come to face the problem of converting image path into bytes.I have a C library for matching images and i want to pass image from sqlite into library so that the image can be matched with other image, Here is the code block that i receive an image path from sqlite:
private byte matdata[] = new byte[512];
for (Multimedia multdata : multimedialist) {
String log = "Id: " + multdata.getID() + " ,FID: "
+ multdata.getFID() + " ,PATH: " + multdata.getPath();
String imagePath = multdata.getPath();
clibrary.GetTemplateByGen(matdata, matsize);
mret = clibrary.MatchTemplate(refdata, refsize[0], matdata, matsize[0]);
Log.i("MATCH" ,""+mret);
Log.i("PATH" ,""+multdata.getPath());
}
As per code block above ,i need to to convert the value for String imagePath to new byte[512] so that i can pass it on clibrary.GetTemplateByGen(matdata, matsize); as clibrary.GetTemplateByGen("BYTES PASSED AFTER IMAGEPATH CONVERTED TO BYTES[512]", matsize);
I have tried to convert path into bitmap and then into byte as below:
Bitmap bitmap = decodeImg(imagePath, 150, 150);
final int lnth=bitmap.getByteCount();
ByteBuffer dst= ByteBuffer.allocate(lnth);
bitmap.copyPixelsToBuffer( dst);
byte[] bytearray=dst.array();
}public static Bitmap decodeImg(String path, int reqWidth, int reqHeight) {
File file = new File(path);
if (file.exists()) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);'
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
} else
return null;
}`
but still the library can not perform matching for the byte array formed.
Can anyone assist on that as i have spent a lot of time solving the issue ,Thanks in advance

Related

How to compress image without losing its Metadata?

I need to compress images before sending the images to the server via Android app. The images taken via camera are very large and they need to be compressed first. When a image is taken from Camera, there are some properties associated with the image like device model, aperture, location, etc.
I'm trying to compress the image, but during compression, those properties of the images are lost. Please help if there is any missing line of code or any library to compress the images without losing those properties.
private void compressImageAndAddToArrayList(Uri imageURI) {
Bitmap bm = null;
try
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
// bm = Media.getBitmap(mContext.getContentResolver(), imageLoc);
bm = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(imageURI), null, options);
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "VDMS" + File.separator + "Camera");
folder.mkdirs();
String now = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date()).toString();
String fileName = caseID + "_" + now + ".jpg";
File imageFile = new File(folder + File.separator + fileName);
FileOutputStream out = new FileOutputStream(imageFile);
bm.compress(Bitmap.CompressFormat.JPEG, 64, out); // quality ranges from 0-100
bm.recycle();
addDocumentToArrayList(String.valueOf(1), Uri.fromFile(imageFile));
}
catch (Exception e)
{
e.printStackTrace();
}
}

Android BitmapFactory.decodeFile on jpeg file returns null

My app calls the camera to take a picture and save it into my app local directory (getApplicationContext().getFilesDir()) which works fine.
When I try to convert the picture into a bitmap using BitmapFactory the result is null. This the code I use :
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
String picturePath = pictureFile.getAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);
Note that pictureFile was created as follows :
pictureFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
foodwarnDir /* directory */
);
Didn't you forget add permissions READ_EXTERNAL_STORAGE and/or WRITE_EXTERNAL_STORAGE ?
File locationOfFile = new
File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/images");
File destination= new File(locationOfFile , fileName + ".JPG");
FileInputStream fileInputStream;
fileInputStream= new FileInputStream(destination);
Bitmap img = BitmapFactory.decodeStream(fileInputStream);
OR
This is my working code in my project here:
View imageHolder = LayoutInflater.from(this).inflate(R.layout.image_item, null);
ImageView thumbnail = (ImageView) imageHolder.findViewById(R.id.media_image);
try {
String path = uri.getPath();
Bitmap bmImg = BitmapFactory.decodeFile(path);
Point p = new Point();
p.set(100, 100);
Bitmap bitmapp = waterMark(bmImg, mRefNo, p, Color.RED, 90, 60, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Glide.with(this)
.load(stream.toByteArray())
.asBitmap()
.error(R.mipmap.ic_launcher)
.into(thumbnail);
mSelectedImagesContainer.addView(imageHolder);
thumbnail.setLayoutParams(new FrameLayout.LayoutParams(wdpx, htpx));
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps you
other helpful Links1 Link2
Create temp file:
File tempFile = File.createTempFile("temp_file, ".jpg", this.getExternalCacheDir());
get path created:
String mPath = tempFile.getAbsolutePath();
now in you activityResult
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(mPath, options);
use
data.getExtras().get("data");//for getting bitmap
Uri u = intent.getData();// for getting the Uri and get the path from uri
for getting data from your camera
Assuming you're using java.io.File class. According to Java docs function .createTempFile creates empty file on the System.
As such, this file will have only meta info without any content, with zero length, and this is probably a reason why it is not possible to extract Bitmap.
So you need to Create File Object instance instead of actual file, using new File()
You can also use WeakReference and similar to Bitmap you create if you're looking to decrease chance of memory leaks in early implementation.

Uri vs File vs StringPath in android

Recently I am doing app deals with saving image and loading image on external storage. I am quite confused with Uri, File and StringPath.
For example, when load image from Gallery, it uses Uri.
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { //Browse Gallery is requested
//Get the path for selected image in Gallery
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
//Access Gallery according to the path
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
loadImage(picturePath); //load picture according the path
image_View.setImageBitmap(pic); //Show the selected picture
}
Then when decode the image, it uses StringPath.
private void loadImage(String picturePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath,options);
int height_ = options.outHeight;
int width_ = options.outWidth;
float ratio = width_/height_;
int width = 480;
int height = 480;
if(width_>height_){
height = Math.round(width / ratio);
}else{
width = Math.round(width*ratio);
}
options.inSampleSize = calculateInSampleSize(options, width, height);
options.inJustDecodeBounds = false;
pic=BitmapFactory.decodeFile(picturePath,options);
}
Then when read byte from file, it uses File.
File cacheDir = getBaseContext().getCacheDir();
//Form a directory with a file named "pic"
File f = new File(cacheDir, "pic");
try {
//Prepare output stream that write byte to the directory
FileOutputStream out = new FileOutputStream(f);
//Save the picture to the directory
pic.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
So, what is the difference? Is it just different in usage but represent same directory?
Content URI looks something like:
content://media/external/images/media/53
The role of ContentResolver here is to get you an access to the image based on this URI, you don't need to know the filename or other properties of the file, you just need this URI to access the image.
String Path is the physical address of the image that stored which looks like:
file:///mnt/sdcard/myimage.jpg
and finally, File is the lowest handler which you need to operate with files. It uses the String Path as argument to create or open the file for read/write.
In your provided example here is the progress:
1- You ask ContentResolver to give you the real file path based on the provided URI
2- you load a bitmap file to a pic object based on the provided Path
3- you create a file named "pic" and compress the pic object to JPG and write to it

image view Shared preferences

I'm newbie in android. My question is how to set shared preferences in image view. I want to shared the image to another activity. Please help me because I'm stocked on it.. Please help me the explain me clearly and codes. Thank you.
The "standard" way to share data across Activities is usign the putExtraXXX methods on the intent class. You can put the image path in your intent:
Intent intent = new Intent(this,MyClassA.class);
intent.putExtra(MyClassA.IMAGE_EXTRA, imagePath);
startActivity(intent);
And you retrieve it and open it in your next Activity:
String filePath = getIntent().getStringExtra(MyClassA.IMAGE_EXTRA);
Here is an implementation of a function that opens and decodes the image and return a Bitmap object, notice that this function requires the image to be located in the assets folder:
private Bitmap getImageFromAssets(String assetsPath,int reqWidth, int reqHeight) {
AssetManager assetManager = getAssets();
InputStream istr;
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
istr = assetManager.open(assetsPath);
bitmap = BitmapFactory.decodeStream(istr, null, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(istr, null, options);
} catch (IOException e) {
return null;
}
return bitmap;
}

How to speed up opening .png bitmaps on Android?

Welcome all
actually i'm opening png files from assets folder with this code:
public static Bitmap loadImage( String imageName ){
if( imageName.charAt(0) == '/' ) {
imageName = imageName.substring(1);
}
imageName = imageName + ".png";
Bitmap image = BitmapFactory.decodeStream(getResourceAsStream(imageName));
return image;
}
public static InputStream getResourceAsStream( String resourceName ) {
if( resourceName.charAt(0) == '/' ) {
resourceName = resourceName.substring(1);
}
InputStream is = null;
try {
is = context.getAssets().open( resourceName );
} catch (IOException e) {e.printStackTrace();}
return is;
}
This code opens the bitmaps with full cuality and it takes a lot of time to open it.
Also any sugerences to speed up the opening of the bitmap will be welcome
Thanks in advance
You can reduce the image size, setting how the image will be subsample on the moment it is loaded from file:
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inSampleSize= 2; // When 2, the orignal width will be divided by 2, and the height too.
Bitmap bmSource = BitmapFactory.decodeFile(path, opt);
If you need to load from a InputStream do that:
BitmapFactory.decodeStream(inputStream, null, opt);

Categories

Resources