How to get bitmap from imagebutton - java

I have ImageButton when click on it gallery will appear for pick an image and send bitmap back to show on this ImageButton.
But I have to get bitmap that has been shown on this ImageButton and then save it into database as byte[]

first get the bitmap from the ImgaeButton
Bitmap bitmap = ((BitmapDrawable)imageButton.getDrawable()).getBitmap();
then convert this bitmap to byteArray
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] byteArray = outputStream.toByteArray();

When you load image from gallery, you already have the URI reference to it, or you have the bitmap. Hope the following helps
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
Now, if you want to get bitmap from imageButton, you can use
Bitmap bitmap = ((BitmapDrawable)imageButton.getDrawable()).getBitmap();
Refer How to get Bitmap from an Uri? as well, to know more

Try
Bitmap bitmap = ((BitmapDrawable)imageButton.getDrawable()).getBitmap();

You can use a blob to store an image in sqlite android internal db.
*** below answer is completely copied from How to store image in SQLite database - credit goes to answer provider
public void insertImg(int id , Bitmap img ) {
byte[] data = getBitmapAsByteArray(img); // this is a function
insertStatement_logo.bindLong(1, id);
insertStatement_logo.bindBlob(2, data);
insertStatement_logo.executeInsert();
insertStatement_logo.clearBindings() ;
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
to retrieve a image from db
public Bitmap getImage(int i){
String qu = "select img from table where feedid=" + i ;
Cursor cur = db.rawQuery(qu, null);
if (cur.moveToFirst()){
byte[] imgByte = cur.getBlob(0);
cur.close();
return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
}
if (cur != null && !cur.isClosed()) {
cur.close();
}
return null ;
}

Related

Error when trying to convert ImageView to string

I have a ImageView that I need to create and get the bitmap of and convert to string, because I need to send the image to charquopy for procesisng. When I attempt to get the Image as a string I get the following error below:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
on this line specifically: imageString = getStringImage(bitmap);
the entire code snipped of that related to my problem:
mImageView = (ImageView) findViewById(R.id.frame_image);
#Override
protected void onCreate(final Bundle savedInstanceState) {
String imageString = "";
BitmapDrawable drawable;
Bitmap bitmap;
drawable = (BitmapDrawable)mImageView.getDrawable();
bitmap = drawable.getBitmap();
imageString = getStringImage(bitmap); // Error occurs in this line
}
the frame image XML:
<ImageView
android:id="#+id/frame_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/camera_view"
android:layout_alignLeft="#id/camera_view"
android:layout_alignRight="#id/camera_view"
android:layout_alignTop="#id/camera_view" />
Output:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
I'd like to know why is it returning a null pointer given that Imageview seems to be apparently properly called.
You can draw the imageview on a canvas and create a bitmap out of it like this
ImageView mImageView = (ImageView) findViewById(R.id.frame_image);
Bitmap bitmap = Bitmap.createBitmap(mImageView .getWidth(), mImageView .getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
mImageView.draw(canvas);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
String imageAsString =Base64.encodeToString(b, Base64.DEFAULT);
//Upload imageAsString
You can try this way
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import java.io.ByteArrayOutputStream;
public class ImageUtil
{
public static Bitmap convert(String base64Str) throws IllegalArgumentException
{
byte[] decodedBytes = Base64.decode(
base64Str.substring(base64Str.indexOf(",") + 1),
Base64.DEFAULT
);
return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
}
public static String convert(Bitmap bitmap)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
}
}

Data is not inserting to database when image is null

I want to store data into the database and want to upload an image in optional.
It means that if i am inserting the record without adding image then it will store in database without the image name.
right now when i am fill the data and insert an image then it is storing in the database if i don't select any image and i add only data then in database the data is not inserted and showing me blank value in every field
I tried a lot but not getting the required output.
My code main.java
buy_image1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
edit.putInt("ImageID", 1);
edit.commit();
}
});
public void selectImage()
{
i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
/*i.putExtra("crop", "true");
i.putExtra("outputX", 512);
i.putExtra("outputY", 512);
i.putExtra("aspectX", 1);
i.putExtra("aspectY", 1);
i.putExtra("scale", true);
*/
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
Uri selectedImage = data.getData();
int imgid = 0;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Log.d("Value", picturePath);
fileName = new File(picturePath).getName();
// imgname.setText(fileName);
String fileNameSegments[] = picturePath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
// MyParams.put("filename", fileName);
Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath);
sp = getActivity().getSharedPreferences("Image ID", Context.MODE_PRIVATE);
imgid = sp.getInt("ImageID", 0);
Log.d("IMGID", Integer.toString(imgid));
BitmapFactory.Options options =null;
options = new BitmapFactory.Options();
options.inSampleSize = 5;
bitmap = BitmapFactory.decodeFile(picturePath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
if(imgid == 1) {
buy_image1.setImageBitmap(yourSelectedImage);
img1 = fileName;
encodedStringIMG1 = encodedString;
}else if(imgid == 2){
buy_image2.setImageBitmap(yourSelectedImage);
img2 = fileName;
encodedStringIMG2 = encodedString;
}
else{
Log.d("IMGID","IMAGE ID IS 0");
}
}
private void InsertWodinformation() {
service(strwodname,strbranch,strcontactperson,strcontact,strwhatsapp,stremail,
strspinnercity,straddress,opendate1,birthdate,ani,strpancard,strtinnumber,strbankname,strbankholdername,strbankac,
strbankcity, strifsccode,strsecuritycheque,strrefrence1,strrefrence2,strremarks,img1,encodedStringIMG1,img2,encodedStringIMG2);
}
private void service(
String strwodname,String strbranch,
String strcontactperson, String strcontact,
String strwhatsapp, String stremail, String strspinnercity,
String straddress, String opendate1, String birthdate, String ani,
String strpancard, String strtinnumber, String strbankname, String strbankholdername
,String strbankac,String strbankcity, String strifsccode,String strsecuritycheque,String strrefrence1,
String strrefrence2,String strremarks,String i1,String encode1,String i2,String encode2
) {
class AddVisitclass extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> param = new HashMap<String, String>();
/*param.put("firm", params[1]);
param.put("oname", params[2]);
param.put("pname1", params[3]);
param.put("pname2", params[4]);
*/
param.put("wname", params[0]);
param.put("branch", params[1]);
param.put("cname", params[2]);
param.put("contact", params[3]);
param.put("whatsapp", params[4]);
param.put("email", params[5]);
param.put("city", params[6]);
param.put("address", params[7]);
param.put("odate", params[8]);
param.put("bdate", params[9]);
param.put("adate", params[10]);
param.put("pancard", params[11]);
param.put("tinno", params[12]);
param.put("bnm", params[13]);
param.put("bank_ac_holder", params[14]);
param.put("bank_ac_no", params[15]);
param.put("bcity", params[16]);
param.put("ifsc_code", params[17]);
param.put("cheque", params[18]);
param.put("ref1", params[19]);
param.put("ref2", params[20]);
param.put("remarks", params[21]);
param.put("pan", params[22]);
param.put("epan", params[23]);
param.put("aadhar", params[24]);
param.put("eaadhar", params[25]);
/*
param.put("light", params[26]);
param.put("elight", params[27]);
param.put("vat", params[28]);
param.put("evat", params[29]);
param.put("vcard", params[30]);
param.put("evcard", params[31]);
param.put("shop", params[32]);
param.put("eshop", params[33]);
*/
param.put("username",uid);
String result = ruc.sendPostRequest(url_addwod, param);
Log.d("Result", result);
Log.d("Data", param.toString());
return result;
}
//#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//loading.dismiss();
Toast.makeText(getActivity(), "W.O.D. added successfully...!!!", Toast.LENGTH_LONG).show();
/* FragmentTransaction t = getActivity().getSupportFragmentManager().beginTransaction();
TabFragment mFrag = new TabFragment();
t.replace(com.Weal.sachin.omcom.R.id.framelayout, mFrag);
t.commit();
*/
}
}
AddVisitclass regi = new AddVisitclass();
regi.execute(strwodname,strbranch,strcontactperson,strcontact,strwhatsapp,stremail,
strspinnercity,straddress,opendate1,birthdate,ani,strpancard,strtinnumber,strbankname,strbankholdername,strbankac,
strbankcity, strifsccode,strsecuritycheque,strrefrence1,strrefrence2,strremarks,i1,encode1,i2,encode2);
}
And one more thing when image is uploading to the server it is generating the lower size but i want it in default size.
The best way to store images/files data is to save the images to the device storage resource (e.g internal memory or external),then you have the image URL/URI saved in your database (instead of having blob field in the database), and to display it all you have to do is to retrieve the file URL and display it on the device.
I hope this gives you a better solution for this issue.
The best way to save images are save them in your computer or device you are using and pass the path (location) of the image through a sql query to the database and when you want to access the image get the location of the image from the database and display.
following link will help you to understand
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
Consider first compressing your images, to reduce the size of the image for storage. You have three options here, first you can get the base64 representation of the image, which is a string then store it , or get the byte array output and still store it. And lastly store the uri reference for the image located on the phone. Though i would not recommend this approach, because it is subjected to path changes and user deletion.
Here is a great library that uses google webp.WebP is a modern image format that provides superior lossless and lossy compression for images.WebP lossless images are 26% smaller in size compared to PNGs. WebP lossy images are 25-34% smaller than comparable JPEG images at equivalent SSIM quality index. Link to library.
Here is a galore of code snippets that can perform your request!
private static String CompressJPEG(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteFormat = stream.toByteArray();
return Base64.encodeToString(byteFormat, Base64.DEFAULT);
}
private static byte[] CompressJPEGByteArray(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
return stream.toByteArray();
}
private static String CompressPNG(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteFormat = stream.toByteArray();
return Base64.encodeToString(byteFormat, Base64.DEFAULT);
}
private static byte[] CompressPNGByteArray(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}
private static Bitmap RevertImageBase64(String encodedImage) {
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}
public static Bitmap RevertFromByteArray(byte[] arr) {
return BitmapFactory.decodeByteArray(arr, 0, arr.length);
}
Here is also code to get the extension from a uri.
public static void GetExtensionFromContentURI(Context context, Uri uri) {
ContentResolver cR = context.getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = mime.getExtensionFromMimeType(cR.getType(uri));
}
Hope this helps :)
You have to covert bitmap to BLOB format to save it ti db llook below
code :
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encodedData = Base64.encodeToString(byteArray, Base64.DEFAULT);
dba.insertPhoto(byteArray);
Regarding the size issue you mentioned, in onActivityResult(), the statement:
options.inSampleSize = 5;
could be the reason for the file to be smaller than the original image.
This is needed for the ImageView. Before compressing, keep a non compressed coopy for transmission to the server.
To troubbleshoot the insert of the image you need to post:
If the column in the database is defined as "not null"
A Log.d() of the value it is sending to the server when no picture is selected.
The code on the server that receives the data and performs runs the insert.
Refactoring code like below might help you. Don't take method names, variable names and other parts as a real example. I wanted to give you a bird-eye view of sample design.
//controller of user request.
handleRequest(){
String imagePath=null;
if(imageExists){ //if user sent image to server.
imagePath=saveImageAndReturnImagePath(...);
}
saveRecordToDB(request.getText(), imagePath);
}
//save image to disk and return image path.
private String saveImageAndReturnImagePath(...){
//do image manipulation here, save image to disk, return path.
return imagePath;
}
//insert a new record to db.
private void saveRecordToDB(String text, imagePath){
Record a=new Record(text, imagePath);
dao.save(a);
}
The simplest way to cache images . is to use JakeWharton/picasso2-okhttp3-downloader
Here's an example :
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.networkInterceptors().add(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder().header("Cache-Control", "max-age=" + (60 * 60 * 24 * 365)).build();
}
});
try{
okHttpClient.setCache(new Cache(this.getCacheDir(), Integer.MAX_VALUE));
OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient);
Picasso picasso = new Picasso.Builder(this).downloader(okHttpDownloader).build();
picasso.load("pucul").error(R.drawable.teacher).into(imgvw);
}
catch (Exception e){
add this to your gradle file
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
Source :

Load image to bitmap and get OutOfMemoryError Exception

I want to load a lot of image like instagram do but still get OutOfMemory my code load 18 image at a time and can scroll down to load more.
I also cache image to disk and resize image to fit thumbnail before load to Bitmap
private Bitmap loadBitmap(String id) throws IOException{
String key = id.toLowerCase();
// Check disk cache in background thread
Bitmap image = cacher.get(key);
if (image == null){
// Not found in disk cache
// Process as normal
if(!isCancelled()){
//download image to stream
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DriveApiActivity.getService().files().get(id)
.executeMediaAndDownloadTo(stream);
//decode image to byte array
byte[] byteArray = stream.toByteArray();
stream.close();
//decode byte array to bitmap file
image = decodeToBitmap(
byteArray,
CustomCardView.width,
CustomCardView.height);
// Add final bitmap to caches
cacher.put(key, image);
}
}
return image;
}
the Logcat say exception is come out of cacher.get() method
public Bitmap get(String key) {
synchronized (diskCacheLock) {
// Wait while disk cache is started from background thread
while (diskCacheStarting) {
try {
diskCacheLock.wait();
} catch (InterruptedException e) {
Toast.makeText(
context,
"getBitmapFromCache:" + e.getMessage(),
4).show();
}
}
if (diskLruCache != null) {
Bitmap bitmap = null;
DiskLruCache.Snapshot snapshot = null;
try{
snapshot = diskLruCache.get(key);
if(snapshot == null){
return null;
}
final InputStream in = snapshot.getInputStream(0);
if(in != null){
final BufferedInputStream buffIn =
new BufferedInputStream(in, Utils.IO_BUFFER_SIZE);
bitmap = BitmapFactory.decodeStream(buffIn);
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(snapshot != null){
snapshot.close();
}
}
if(BuildConfig.DEBUG){
Log.d( "cache_test_DISK_", bitmap == null ? "" : "image read from disk " + key);
}
return bitmap;
}
}
return null;
}
this code come from DiskLruCache google provided
You have to use:
largeheap = true
in android. manifest file, from this line you cannot get out of memory error
It will solve your problem

How to resize image that captured from camera and display on imageview

now i develop an android app that need to upload image to my server. but when i try load image to imageview it just show blank. when i change the resolution from 1300 pixels to 300 pixels then the image can display at ImageView. my Code i like below. Please help
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
viewImage = (ImageView)findViewById(R.id.imgInv);
int width = viewImage.getWidth();
int height = viewImage.getHeight();
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = true;
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOptions.inDither = true;
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
viewImage.setImageBitmap(bitmap);
OutputStream outFile = null;
File file = new File(path,String.valueOf(System.currentTimeMillis()) + ".jpg");
imgName = mName + "_" + String.valueOf(System.currentTimeMillis());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, baos);
byte[] b = baos.toByteArray();
imgData = Base64.encodeToString(b,Base64.DEFAULT);
}
}
I'm not talking about your code but there is a library for what you want. You can use Picasso library that has complete features for working on images like as downloading, caching etc.
You can get it from here with an example.
Also there is a tutorial about it

How to Create a Blob from Bitmap in Android Activity?

I'm trying to create new MyImage entitly as listed in How to upload and store an image with google app engine.
Now I'm not using any Form. I have Android app that gets Uri from Gallery :
m_galleryIntent = new Intent();
m_galleryIntent.setType("image/*");
m_galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
m_profileButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
startActivityForResult(Intent.createChooser(m_galleryIntent, "Select Picture"),1);
}
});
And I'm using the Uri to create a Bitmap.
How can I create a Blob In my client from the Bitmap?
And what jars i'll have to add to my android project?
Is this a proper way to use Blob?
My main goal is to save an image uplodaed from an android in the GAE datastore, Am Using this tools properly or ther is better way?
Thatks.
You have to convert your Bitmap into a byte[]and after you can store it in your database as a Blob.
To convert a Bitmap into a byte[], you can use this :
Bitmap yourBitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
yourBitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] bArray = bos.toByteArray();
I hope it's what you want.
you can use this code :
public static byte[] getBytesFromBitmap(Bitmap bitmap) {
if (bitmap!=null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
return null;
}
for converting bitmap to blob.
note:
blob is an binary large object.

Categories