how to store picture in MySQL using android - android

I trying to develop an android application that enables the user to add a picture from his gallery, it works fine and displays the picture in the image view.
the problem is I am trying to save this picture in MySQL database (not URL or path of it) I want to store as a blob.
I tried the below code to get the image from user's gallery and display it in the image view.
The attribute test2 is a string and it is what I save in the database
if (requestCode == GET_FROM_GALLERY && resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
}
////// edit
Bitmap image = BitmapFactory.decodeFile(imagepath);
FinalBytes = getBytes(image); // this will be save in DB
Bitmap getIt = getBitmap(FinalBytes);
imgV.setImageBitmap(getIt);
imgV.setDrawingCacheEnabled(true);
imgV.buildDrawingCache();
Bitmap testbit = imgV.getDrawingCache();
ByteArrayOutputStream testbyte = new ByteArrayOutputStream();
testbit.compress(Bitmap.CompressFormat.JPEG, 100, testbyte);
testbyte2 = testbyte.toByteArray();
base64Image = Base64.encodeToString(testbyte2, Base64.DEFAULT);
I used below code for retrieving the image
byte[] decodedString = Base64.decode(Recipes[position].getRimage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.image.setImageBitmap(decodedByte);
But I am getting this message when decoding it.
illegalargumentexception bad base 64
please help I spent 2 days on this error

Related

Adding image from gallery and saving to pdf in adroid studio

I made an app in android studio (Java) on which is possible to fill some brief data in text boxes. Also app has two buttons, one for loading image from gallery and one for saving complete data to pdf.
I can successfully save all text data, but have problem with loaded image. Image is sucessfully loaded to app, but i dont know hot to save it to pdf. Image is loaded as an ImageView object.
Just to mention for pdf part i use itext.
Pls, help with hints or code for saving ImageVIew object to pdf file.
i had the same problem, but i can fixed.
first i changed the way i used to pick the image and replaced it with this code:
Intent getImage = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(getImage, GALLERY_REQUEST_CODE);
then, in the class onActivityResult i transformed the uri to a bitmap using this:
if(requestCode==GALLERY_REQUEST_CODE && resultCode== RESULT_OK && data!=null){
Uri imageData = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageData,filePath,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String myPath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(myPath);
then passed the bitmap to the pdf
pdf.addFoto(bitmap);
and finally, in the pdf template i used this to put the image in a table:
public void addFoto (Bitmap u) {
try{
PdfPTable tabla = new PdfPTable(1);
tabla.setWidthPercentage(60);
tabla.setSpacingBefore(10);
tabla.setSpacingAfter(10);
Bitmap bmp = u;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
PdfPCell imageCell = new PdfPCell();
imageCell.addElement(image);
tabla.addCell(imageCell);
document.add(tabla);
Look into PdfDocument
Example from the documentation
// create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(new Rect(0, 0, 100, 100), 1).create();
// start a page
Page page = document.startPage(pageInfo);
// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());
// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());
// close the document
document.close();

In the android application, image isn't showing after closing app and restarting it

In an app I am allowing user to pick image from gallery or he can choose from camera. Though I can manage the image and show it in the activity in the first time, after closing the app and restarting it, the image is gone and the space is blank.There was an explanation given to me to save the image data in sharedPreferences but I am new in android and don't pretty much understand. I looked for sharedPreferences but don't know how to make it work.
So if anybody help kindly with some explanation and code, it would help me a lot.
Thanks.
Here is what I tried to do.
private void openCamera(){
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,getPhotoFileUri(photoFileName)); // set the image file name
// If you call startActivityForResult() using an intent that no app can handle, your app will crash.
// So as long as the result is not null, it's safe to use the intent.
if (intent.resolveActivity(getPackageManager()) != null) {
// Start the image capture intent to take photo
startActivityForResult(intent, TAKE_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// final android.widget.LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imageview.getLayoutParams();
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
imageview.setImageURI(imageUri);
//selectedImagePath = getPath(imageUri);
//ystem.out.println("Image Path : " + selectedImagePath);
}
else if (requestCode == TAKE_IMAGE && resultCode == Activity.RESULT_OK) {
Uri takenPhotoUri = getPhotoFileUri(photoFileName);
// by this point we have the camera photo on disk
Bitmap rawTakenImage = BitmapFactory.decodeFile(takenPhotoUri.getPath());
// RESIZE BITMAP, see section below
// See BitmapScaler.java: https://gist.github.com/nesquena/3885707fd3773c09f1bb
// Get height or width of screen at runtime
int screenWidth = DeviceDimensionsHelper.getDisplayWidth(this);
// Resize a Bitmap maintaining aspect ratio based on screen width
Bitmap resizedBitmap = BitmapScaler.scaleToFitWidth(rawTakenImage,screenWidth);
// Load the taken image into a preview
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// Compress the image further
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
// Create a new file for the resized bitmap (`getPhotoFileUri` defined above)
Uri resizedUri = getPhotoFileUri(photoFileName + "_resized");
File resizedFile = new File(resizedUri.getPath());
// Write the bytes of the bitmap to file
try{
resizedFile.createNewFile();
FileOutputStream fos = new FileOutputStream(resizedFile);
fos.write(bytes.toByteArray());
fos.close();
}catch (IOException e){
System.out.println("Error occured");
}
imageview.setImageBitmap(rawTakenImage);
}
}
public Uri getPhotoFileUri(String fileName) {
// Only continue if the SD Card is mounted
if (isExternalStorageAvailable()) {
// Get safe storage directory for photos
// Use `getExternalFilesDir` on Context to access package-specific directories.
// This way, we don't need to request external read/write runtime permissions.
File mediaStorageDir = new File(
getExternalFilesDir(Environment.DIRECTORY_PICTURES), APP_TAG);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){
Log.d(APP_TAG, "failed to create directory");
}
// Return the file target for the photo based on filename
return Uri.fromFile(new File(mediaStorageDir.getPath() + File.separator + fileName));
}
return null;
}
// Returns true if external storage for photos is available
private boolean isExternalStorageAvailable() {
String state = Environment.getExternalStorageState();
return state.equals(Environment.MEDIA_MOUNTED);
}
You can use below ways to store image.
1. Database with Base64
You can convert image into base64 string and store in database.
So when you open application you can retrieve base64 String from database and display image in ImageView.
2. Store Image Path in Database
You can store image path in database, when you open application, just retrieve image path and display image in ImageView.
But if you delete image from memory, you will not get image from iamge path.
3. Store Image in Server.
If you store image in server, you can retrieve image path and download image using AsyncTask or sime 3rd party liberary. And display image in ImageView.
(Liberaries : Picaso, LazyLoading etc.)

Send image to server from gallery android bitmap

I tried to send an image to server from gallery, I compressed it with Base64.
I started an activity for gallery:
private void startGalleryActivity() {
Intent intent = new Intent();
intent.setType("image/*");
String selectPicture = getResources().getString(R.string.select_picture);
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, GALLERY);
}
I received the result in onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY && resultCode == MainActivity.RESULT_OK) {
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
// Now we need to set the GUI ImageView data with data read from the picked file.
imageView.setImageBitmap(BitmapFactory.decodeFile(imagePath));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeFile(imagePath, options);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
Server s = new Server("new");
s.send(encoded);
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
super.onActivityResult(requestCode, resultCode, data);
When I send the image to serve the size of it is 4 times higher. If I write the image after I read it, this is write with double size. Why do I have this overhead?
Why do I have this overhead?
In addition to the Base64 overhead itself, you are re-encoding the image as a PNG. If the image started as something else, like a JPEG, a PNG version of that image may be substantially larger.
Also, please delete the four lines preceded by // Let's read picked image path using content resolver. First, that code will fail on hundreds of millions of Android devices, because a Uri is not a file, and you cannot assume that you can get a local filesystem path for that data. Second, you do not need it, as BitmapFactory has a decodeStream() method that you can use with getContentResolver().openInputStream(pickedImage).
In addition, please do not call decode...() on BitmapFactory twice. Load the bitmap once. Use the bitmap both for the ImageView and for your uploading.
Calling compress on a PNG will not make your file smaller as it is already compressed. Converting a binary file to a text stream
will really make it big. To avoid less overhead by converting the PNG file
to text file, just send the file as is, as a byte array. And add the file length
in the header. You can use DataOutputStream to do this.
byte[] byteArray = byteArrayOutputStream .toByteArray();
ByteArrayOutputStream btOS = new ByteArrayOutputStream();
DataOutputStream dataOS = new DataOutputStreamEx(btOS);
dataOS.writeInt(byteArray.length); // length of file
dataOS.write(byteArray); // actual file
dataOS.write(0); // end of field
dataOS.close()
I don't know what you are using in the backend, but you can just read
the first 4 bytes of what you will receive and that will be the length
of you file. And use that length to read the entire file.
It will be approximately 37% larger:
Very roughly, the final size of Base64-encoded binary data is equal to
1.37 times the original data size
Source: http://en.wikipedia.org/wiki/Base64
You are using Bitmap and BitmapFactory to convert a small jpg file to a big png file. Why aren't you sending the jpg directly? So do NOT use Bitmap and BitmapFactory to begin with. You end up else with something that was not your file.

pick image from gallery and convert into byte data how?

I need to pick an image from gallery and then convert it into byte data. I know how to pick image from gallery. Also I know how to convert image to byte data. But problem is i convert image that are in drawable but now I need to pick it from gallery and convert it to byte code. Any help
THanks
In onClick function I am using this code to pick image from gallery
Intent image = new Intent(Intent.ACTION_GET_CONTENT);
image.setType("Image/*");
startActivityForResult(image, 0);
And I have used following code to convert image that is in drawable to byte data.
bm = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
data = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 40 , data);
bitmapdata = data.toByteArray();
Now how would i convert image from gallery to byte data.
Thanks
In onActivityResult you will receive the Uri to your selected image like this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_IMAGE && data != null && data.getData() != null){
Uri imageUri = data.getData();
//....
}
}
Then to retrieve it from the MediaStore you should use :
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
after that, you should process the Bitmap like you do it now.

How to restrict user to select image below 500kb from gallery? [duplicate]

This question already has an answer here:
How resize image from gallery?
(1 answer)
Closed 3 years ago.
I need too display a image in ImageView and upload to server by fetching from gallery. I have got a problem that I should allow the user to send image file more than 500kb. How to restrict the user to choose below 500kb. Or is there any way to compress the Image to PNG format which I got form Uri. Please need a solution
My Code follows:
if(requestCode == Constants.SELECT_PICTURE && resultCode == RESULT_OK){
if(data != null)
{
photoUri = data.getData();
if (photoUri != null)
{
try {
bMap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
Bitmap bitMap = Bitmap.createScaledBitmap(bMap, 320, 480, false);
cabinImge.setImageBitmap(bitMap);
Utility.releaseImgViewMemory(cabinImge);
uploadImage(bitMap);
}catch(OutOfMemoryError e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
When you select an image from the gallery in your app, it will return a URI for that image. You can then retrive its size and apply calculation on that simply byte/1024

Categories

Resources