Showing posts with label imageview. Show all posts
Showing posts with label imageview. Show all posts

Thursday, July 5, 2018

How to load Cipher encrypted image file in ImageView without saving to device

Leave a Comment

I am creating an application with content security for no one could ever copy the contents and files. I am using cipher to encrypt the image directly from the URL, with out downloading to the device. Please find my code below.

URL url = new URL(images.getImageurl()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); File folder = new File(Environment.getExternalStorageDirectory(), "zerb"); boolean success = true;  if (!folder.exists()){ folder.mkdirs(); } InputStream fis = connection.getInputStream(); String path = folder.getAbsolutePath() + "images.getImageName + ".jpg"; encryptfile(fis, path, AppConstants.password + images.getContentid() + images.getTopicid()) fis.close(); 

And the cipher encryption Method code is

private static boolean encryptfile(InputStream inputStream, String path, String password) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {      FileOutputStream fos = new FileOutputStream(path.concat(".crypt"));     byte[] key = (AppConstants.salt + password).getBytes("UTF-8");     MessageDigest sha = MessageDigest.getInstance("SHA-1");     key = sha.digest(key);     key = Arrays.copyOf(key, 16);     SecretKeySpec sks = new SecretKeySpec(key, "AES");     Cipher cipher = Cipher.getInstance("AES");     cipher.init(Cipher.ENCRYPT_MODE, sks);     CipherOutputStream cos = new CipherOutputStream(fos, cipher);     int b;     byte[] d = new byte[8];     while ((b = inputStream.read(d)) != -1) {         cos.write(d, 0, b);     }     cos.flush();     cos.close();     inputStream.close();     File encryptedFile = new File(path.concat(".crypt"));     return (encryptedFile.exists()); } 

and the decryption code is

 public static void decrypt(String path, String password, String outPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {     FileInputStream fis = new FileInputStream(path);     FileOutputStream fos = new FileOutputStream(outPath);     byte[] key = (AppConstants.salt + password).getBytes("UTF-8");     MessageDigest sha = MessageDigest.getInstance("SHA-1");     key = sha.digest(key);     key = Arrays.copyOf(key, 16);     SecretKeySpec sks = new SecretKeySpec(key, "AES");     Cipher cipher = Cipher.getInstance("AES");     cipher.init(Cipher.DECRYPT_MODE, sks);     CipherInputStream cis = new CipherInputStream(fis, cipher);     int b;     byte[] d = new byte[8];     while ((b = cis.read(d)) != -1) {         fos.write(d, 0, b);     }     fos.flush();     fos.close();     cis.close(); } 

If I decrypt the image, it will be shown and can be copied from the device. All I need is to load the encrypted image to an ImageView without saving the decrypted image to the device, so that no one can copy. Please someone help me.

1 Answers

Answers 1

An ImageView can show an in-memory android.graphics.Bitmap which can be read in directly from an InputStream.

For example, the decrypt() method could be adapted to return a Bitmap :

public Bitmap decrypt(String path, String password) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {     FileInputStream fis = new FileInputStream(path);     byte[] key = (AppConstants.salt + password).getBytes("UTF-8");     MessageDigest sha = MessageDigest.getInstance("SHA-1");     key = sha.digest(key);     key = Arrays.copyOf(key, 16);     SecretKeySpec sks = new SecretKeySpec(key, "AES");     Cipher cipher = Cipher.getInstance("AES");     cipher.init(Cipher.DECRYPT_MODE, sks);     CipherInputStream cis = new CipherInputStream(fis, cipher);      Bitmap bitmap = BitmapFactory.decodeStream(cis);     cis.close();      return bitmap; } 

(Although it's called Bitmap, it's fine to decode a .jpg or .png).

Then this can be shown in the ImageView:

ImageView imageView = findViewById(R.id.imageView); Bitmap bitmap = decrypt(path + ".crypt", password); imageView.setImageBitmap(bitmap); 
Read More

Thursday, May 24, 2018

Adding ImageView crashes android app widget

Leave a Comment

I am making a very simple widget that shows an image using ImageView.

My layout Looks like this

<RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:padding="16dip">      <!-- ImageView logo -->     <ImageView         android:id="@+id/logo"         android:src="@drawable/giants"         android:contentDescription="@string/app_name"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_centerInParent="true"         android:scaleType="fitXY" />  </RelativeLayout> 

My Widget Provider Class Looks like this

 public class LogoWidgetProvider extends AppWidgetProvider {      @Override     public void onUpdate(Context context, AppWidgetManager      appWidgetManager, int[] appWidgetIds) {          // What Happens While App Goes Through Each Widget Id//         for (int currentWidgetId: appWidgetIds) {              // Define And Instantiate Variable RemoteViews widgetLogo//             RemoteViews widgetLogo = new RemoteViews(context.getPackageName(), R.layout.widget_logo);              // Update Widget//             appWidgetManager.updateAppWidget(currentWidgetId, widgetLogo);         }     } } 

The receiver in my manifest looks like this

    <!-- Widget Provider Logo -->     <receiver android:name=".LogoWidgetProvider">          <!-- Tell The App That There Is A Widget To Display -->         <intent-filter>             <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />         </intent-filter>          <!-- Tell The App Where To Find Widget Data -->         <meta-data             android:name="android.appwidget.provider"             android:resource="@xml/appwidget_info_logo">         </meta-data>      </receiver> 

Lastly, the widget provider XML looks like this

<!-- Basic Information For Widget Logo --> <appwidget-provider     xmlns:android="http://schemas.android.com/apk/res/android"     android:initialLayout="@layout/widget_logo"     android:minHeight="110dip"     android:minWidth="110dip"     android:minResizeWidth="40dip"     android:resizeMode="vertical|horizontal"     android:updatePeriodMillis="3600000"     android:widgetCategory="home_screen">  </appwidget-provider> 

For some reason, the widget crashes every time. If I was to switch ImageView To Button it works fine. What am I missing to make the widget display the Image?

Thanks

1 Answers

Answers 1

I figured it out. You can use any image regardless of resolution but it needs to be put inside a box of 400 pixels by 400 pixels. I used paint pad to do it. Once it is in the box the image shows up

Read More

Thursday, December 21, 2017

Background image disappears after navigating back and forth several times React native

Leave a Comment

I have made a simple view with a background image and some icons on top of it. Clicking on icons navigate to different pages. It is working fine. Problem is when I navigate to other pages come back to home page and do this for 7-8 times the background image just disappears from all the screens. Below is the code of home screen and Screenshots

  <Image   source={require('../images/background.jpg')}   style={{     justifyContent:'center',                                                            resizeMode: "stretch",     height: height,     width: width,     alignItems: "center"   }} >   <StatusBar   backgroundColor="#4e0870"   barStyle="light-content"  /> <Image style={{ height: 125, width: 125 }} source={require('../images/guru_logo.png')} />  <View style={{   marginTop: 30,   flexDirection: 'row' }}>   <TouchableOpacity activeOpacity={.5} onPress={() => {     BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);     navigate("LiveTV")   }   }   >     <Image       source={require('../images/live.png')}       style={{         resizeMode: "stretch",         height: 75,         width: 75       }} /></TouchableOpacity>   <TouchableOpacity activeOpacity={.5} onPress={() => {     BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);     navigate("VideoPage")   }}>      <Image       source={require('../images/youtube.png')}       style={{         marginTop: 5,          resizeMode: "stretch",         marginLeft: 100,         height: 75,         width: 75       }} />   </TouchableOpacity> </View> <View    style={{      flexDirection: 'row',     marginTop: 20   }}>   <Text     style={{       marginLeft: -5,       fontSize: 20,       color: "#FFF"     }}>Live Tv</Text>   <Text     style={{       fontSize: 20,       color: "#FFF",       marginLeft: 125     }}>Video</Text> </View> <View   style={{      flexDirection: 'row',     marginTop: 20   }}>   <TouchableOpacity activeOpacity={.5} onPress={() => {     BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);     navigate("FacebookPage")   }}>     <Image       source={require('../images/facebook-logo.png')}       style={{         resizeMode: "stretch",         height: 75,         width: 75       }} /></TouchableOpacity>   <TouchableOpacity activeOpacity={.5} onPress={() => {     BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);     navigate("AudioPage")   }}>     <Image       source={require('../images/icon.png')}       style={{         resizeMode: "stretch",         marginLeft: 100,         height: 75,         width: 75       }} /></TouchableOpacity> </View> <View   style={{      flexDirection: 'row',     marginTop: 20   }}>   <Text     style={{       marginLeft: -20,       fontSize: 20,       color: "#FFF"     }}>Facebook</Text>    <Text     style={{       fontSize: 20,       color: "#FFF",       marginLeft: 110     }}>Audio</Text> </View>  <TouchableOpacity  activeOpacity={.5} onPress={() => {   BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);   navigate("ContactPage") }}>   <Image     source={require('../images/contact.png')}     style={{         marginTop: 20,       resizeMode: "stretch",       height: 75,       width: 75     }} /></TouchableOpacity> <Text style={{   fontSize: 20,   color: "#FFF" }}>Contact Us</Text> </Image>           

invisible view
Normal view

2 Answers

Answers 1

Every time you navigate to that screen, it calls a re-render. I work around i've found in the past is to define your image sources as a variable, and simply reference it in the source = {HERE} section. I've provided some sample code below. This has fixed this issue in the past, let me know how it goes.

var images = {     live: {img: require('../images/live.png')},     guru: {img: require('../images/guru_logo.png')},     background: {img: require('../images/background.jpg')},     //and so on  }  class SelectionScreen extends Component {     //all your other code 

and then in your Image components

<Image source = {images[background].img}.../> 

Answers 2

I think it could be related to this react-native issue: https://github.com/facebook/react-native/issues/13600

I would try to:

  • Run the app on different phones / emulators to see if it depends on device specifications (like RAM and others). If the app is for both Android and iOS I would also try to see if it's same behaviour on both platforms;
  • Replace temporary the images with some other smaller/larger images to see if it changes somehow the issue;
  • Upgrade React Native if necessary and use BackgroundImage component for background images instead of Image.
Read More

Monday, May 8, 2017

Data is not inserting to database when image is null

Leave a Comment

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.

7 Answers

Answers 1

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.

Answers 2

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/

Answers 3

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 :)

Answers 4

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); 

Answers 5

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:

  1. If the column in the database is defined as "not null"
  2. A Log.d() of the value it is sending to the server when no picture is selected.
  3. The code on the server that receives the data and performs runs the insert.

Answers 6

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); } 

Answers 7

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 :

Read More

Wednesday, March 15, 2017

Can't drag and drop a simple imageView in android studio

Leave a Comment

I'm trying to create a simple drag and drop image in android studio. I can get the image to drag around the screen, it disappears as soon as I release it. In the console, I get a "Reporting drop result: false"

Here's my code:

ImageView mImageView; String mString;  private android.widget.RelativeLayout.LayoutParams mLayoutParams;      mImageView.setOnLongClickListener(new View.OnLongClickListener(){         @Override         public boolean onLongClick(View v){             ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());             String[] mimeTypes = {                     ClipDescription.MIMETYPE_TEXT_PLAIN             };             ClipData dragData = new ClipData(v.getTag().toString(), mimeTypes, item);             View.DragShadowBuilder myShadow = new View.DragShadowBuilder(mImageView);              v.startDrag(dragData, myShadow, null, 0);             return true;         }     });      mImageView.setOnDragListener(new View.OnDragListener() {         @Override         public boolean onDrag(View v, DragEvent event) {             switch(event.getAction()) {                 case DragEvent.ACTION_DRAG_STARTED:                     mLayoutParams = (RelativeLayout.LayoutParams)v.getLayoutParams();                     Log.d(mString, "Action is DragEvent.ACTION_DRAG_STARTED");                      // Do nothing                     break;                  case DragEvent.ACTION_DRAG_ENTERED:                     Log.d(mString, "Action is DragEvent.ACTION_DRAG_ENTERED");                     int x_cord = (int) event.getX();                     int y_cord = (int) event.getY();                     break;                  case DragEvent.ACTION_DRAG_EXITED :                     Log.d(mString, "Action is DragEvent.ACTION_DRAG_EXITED");                     x_cord = (int) event.getX();                     y_cord = (int) event.getY();                     mLayoutParams.leftMargin = x_cord;                     mLayoutParams.topMargin = y_cord;                     v.setLayoutParams(mLayoutParams);                     break;                  case DragEvent.ACTION_DRAG_LOCATION  :                     Log.d(mString, "Action is DragEvent.ACTION_DRAG_LOCATION");                     x_cord = (int) event.getX();                     y_cord = (int) event.getY();                     break;                  case DragEvent.ACTION_DRAG_ENDED   :                     Log.d(mString, "Action is DragEvent.ACTION_DRAG_ENDED");                      // Do nothing                     break;                  case DragEvent.ACTION_DROP:                     Log.d(mString, "ACTION_DROP event");                      // Do nothing                     break;                 default: break;             }             return true;         }     });      mImageView.setOnTouchListener(new View.OnTouchListener(){         @Override         public boolean onTouch(View v, MotionEvent event) {             if (event.getAction() == MotionEvent.ACTION_DOWN) {                 ClipData data = ClipData.newPlainText("", "");                 View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(mImageView);                  mImageView.startDrag(data, shadowBuilder, mImageView, 0);                 mImageView.setVisibility(View.INVISIBLE);                 return true;             } else {                 return false;             }         }     }); } 

}

3 Answers

Answers 1

There's one problem with the code that's given that will be easy to fix. The OnDragListener() should be set for the destination (or any possible destination) view. So OnLongClickListener() and OnTouchListener() are set on the source view, imageView then there should be imageView2 for the OnDragListener(). That's a long explanation but should be an easy fix.

See drag-drop for a good example.

The rest of the solution is much more involved if done properly (however, there's a work around).

When starting a drag, basically you need to copy the image to the clipboard, then paste it in the drop view. This requires creating a ContentProvider then using a ContentResolver (link).

Clipboard documentation: ClipData

I have future plans to do this for an app but that won't be happening any time soon so, unfortunately, I won't be able to provide any code.

However, there is a workaround that's much less involved.

Set tag(s) on any image that will potentially be moved.

imageView.setTag("ImageTag1"); 

In onLongClick(), set item and dragData as is done in the question.

Then in OnDragListener(), read the tag, determine which image is being dropped then set that image to the view. Something like this:

case DragEvent.ACTION_DROP:     ClipData.Item item = event.getClipData().getItemAt(0);     CharSequence dragData = item.getText();      if(dragData.equals("ImageTag1")) {         // this gets jpg image from "drawable" folder,         //      set ImageView appropriately for your usage         ((ImageView)v).setImageResource(R.drawable.image1);                                 } else if(dragData.equals("ImageTag2")) {         ((ImageView)v).setImageResource(R.drawable.image2);     }     break; 

You also need to do something similar in case "ACTION_DRAG_EXITED". If the image is dropped in an invalid area, this puts the image back to the original view.

Answers 2

Edited : Changed with a working example of how to move all the views contained in a RelativeLayout using onTouch. I think that onDrag event applies better to drag and drop data items, not to move views.

public class MainActivity extends AppCompatActivity implements View.OnTouchListener {     private RelativeLayout mRelLay;     private float mInitialX, mInitialY;     private int mInitialLeft, mInitialTop;     private View mMovingView = null;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         mRelLay = (RelativeLayout) findViewById(R.id.relativeLayout);          for (int i = 0; i < mRelLay.getChildCount(); i++)             mRelLay.getChildAt(i).setOnTouchListener(this);     }      @Override     public boolean onTouch(View view, MotionEvent motionEvent) {         RelativeLayout.LayoutParams mLayoutParams;          switch (motionEvent.getAction()) {             case MotionEvent.ACTION_DOWN:                 mMovingView = view;                 mLayoutParams = (RelativeLayout.LayoutParams) mMovingView.getLayoutParams();                 mInitialX = motionEvent.getRawX();                 mInitialY = motionEvent.getRawY();                 mInitialLeft = mLayoutParams.leftMargin;                 mInitialTop = mLayoutParams.topMargin;                 break;              case MotionEvent.ACTION_MOVE:                 if (mMovingView != null) {                     mLayoutParams = (RelativeLayout.LayoutParams) mMovingView.getLayoutParams();                     mLayoutParams.leftMargin = (int) (mInitialLeft + motionEvent.getRawX() - mInitialX);                     mLayoutParams.topMargin = (int) (mInitialTop + motionEvent.getRawY() - mInitialY);                     mMovingView.setLayoutParams(mLayoutParams);                 }                 break;              case MotionEvent.ACTION_UP:                 mMovingView = null;                 break;         }          return true;     } } 

Answers 3

This is how I do it in my app:

For the "view" that you want to drag, set this in the onTouchListener:

    public final class ChoiceTouchListener implements OnTouchListener {     Context context;     //int index;     public static float offsetX = 0,offsetY = 0;      DragShadowBuilder shadowBuilder;      public ChoiceTouchListener(Context context) {         super();         this.context = context;         //this.index = index;     }         public boolean onTouch(View view, MotionEvent motionEvent) {         if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {              //view.setTag("option"+index);             ClipData data = ClipData.newPlainText("tag", view.getTag().toString());             shadowBuilder = new View.DragShadowBuilder(view);              //start dragging the item touched             view.startDrag(data, shadowBuilder, view, 0);              offsetX = view.getLeft();//(int)view.getX();//(int)motionEvent.getX();             offsetY = view.getTop();//(int)view.getY();//motionEvent.getY();             view.setVisibility(View.INVISIBLE);             Log.v("here","it is ::" + (int)motionEvent.getX() + " , "+(int)motionEvent.getY());              return false;            }          return true;      } } 

And here's a RelativeLayout that has the destination "view" set in the middle and listens for the drag and drop events:

    public class DragLayout extends RelativeLayout {      boolean DEBUG = true;      AnimationDrawable blenderAnim;     Handler handlerAnim2;     Context context;      private int dimensionInPixel = 200;     int screenWidth,screenHeight;      public DragLayout(Context context) {         super(context);          this.context = context;          //not to include in main program         getDimensionsofScreen();          setLayout();         setViews();      }        private void setLayout() {           // set according to parent layout (not according to current layout)         RelativeLayout.LayoutParams rLp = new RelativeLayout.LayoutParams(                 LayoutParams.MATCH_PARENT,  LayoutParams.MATCH_PARENT);         rLp.topMargin = 2 * (screenHeight / 25); // calculating 1/10 of 4/5         // screen           this.setLayoutParams(rLp);      }      void setViews() {          ImageView img2 = new ImageView(context);          int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());          RelativeLayout.LayoutParams rLp = new RelativeLayout.LayoutParams(                 (screenWidth / 5), (screenHeight / 5));         rLp.topMargin = (screenHeight / 10);         rLp.leftMargin = (4*screenWidth / 10);         rLp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);          img2.setLayoutParams(rLp);         img2.getLayoutParams().height = dimensionInDp;         img2.getLayoutParams().width = dimensionInDp;         img2.setImageDrawable(getResources().getDrawable(R.drawable.blender_anim));         img2.setOnDragListener(new ChoiceDragListener(context));         this.addView(img2);          blenderAnim = (AnimationDrawable)img2.getDrawable();         blenderAnim.setOneShot(true);         blenderAnim.stop();      }       public ArrayList<Integer> getDimensionsofScreen() {          //metrics that holds the value of height and width         DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();;         ArrayList<Integer> vals = new ArrayList<Integer>();          vals.add(displayMetrics.widthPixels);         vals.add(displayMetrics.heightPixels);         screenHeight = displayMetrics.heightPixels;         screenWidth = displayMetrics.widthPixels;          return vals;     }        @SuppressLint("NewApi")     @Override     public boolean onDragEvent(DragEvent event) {          int mCurX = (int) event.getX();         int mCurY = (int) event.getY();          if(event.getAction() == DragEvent.ACTION_DRAG_STARTED || event.getAction() == DragEvent.ACTION_DRAG_ENTERED) {             if (blenderAnim.isRunning()) {                 blenderAnim.stop();             } else {                 blenderAnim.run();                  handlerAnim2 = new Handler();                 handlerAnim2.postDelayed(                         new Runnable(){                              @Override                             public void run() {                                 blenderAnim.stop();                              }},                         getAnimationDuration(blenderAnim));             }         }          if(event.getAction() == DragEvent.ACTION_DROP || event.getAction() == DragEvent.ACTION_DRAG_EXITED) {              if (blenderAnim.isRunning()) {                 blenderAnim.stop();             } else {                 blenderAnim.run();                  handlerAnim2 = new Handler();                 handlerAnim2.postDelayed(                         new Runnable(){                              @Override                             public void run() {                                 blenderAnim.stop();                              }},                         getAnimationDuration(blenderAnim));             }              Log.v("here", "it is :: " + mCurX + ", " + mCurY);              View view1 = (View) event.getLocalState();             view1.setVisibility(View.VISIBLE);             ObjectAnimator animationx = ObjectAnimator.ofFloat(view1,"translationX", mCurX - ChoiceTouchListener.offsetX-(screenWidth / 10),0.0f);             ObjectAnimator animationy = ObjectAnimator.ofFloat(view1, "translationY", mCurY - ChoiceTouchListener.offsetY - (screenHeight / 10), 0.0f);             AnimatorSet animSet = new AnimatorSet();             animSet.setDuration(500);             animSet.playTogether(animationx,animationy);              animSet.start();          }         if(event.getAction() == DragEvent.ACTION_DROP || event.getAction() == DragEvent.ACTION_DRAG_ENDED){             if(blenderAnim.isRunning()){                 blenderAnim.stop();             }         }         return true;       }      private int getAnimationDuration(AnimationDrawable src){         int dur = 0;         for(int i=0; i<src.getNumberOfFrames(); i++){             dur += src.getDuration(i);         }         return dur;     } } 

This is the drag listener for the ImageView in the DragLayout:

    public class ChoiceDragListener implements View.OnDragListener {      boolean DEBUG = true;     Context context;     public String TAG = "Drag Layout:";      public ChoiceDragListener(Context context){         this.context = context;     }      @Override     public boolean onDrag(View v, DragEvent event) {         switch (event.getAction()) {             case DragEvent.ACTION_DRAG_STARTED:                 if(DEBUG) Log.v("here","drag started");                 break;             case DragEvent.ACTION_DRAG_ENTERED:                 break;             case DragEvent.ACTION_DRAG_LOCATION:                 int mCurX = (int) event.getX();                 int mCurY = (int) event.getY();                  if(DEBUG) Log.v("Cur(X, Y) : " ,"here ::" + mCurX + ", " + mCurY );                  break;             case DragEvent.ACTION_DRAG_EXITED:                  if(DEBUG)                     Log.v("here","drag exits");                  break;             case DragEvent.ACTION_DROP:                  //handle the dragged view being dropped over a drop view                 View view = (View) event.getLocalState();                 ClipData cd =  event.getClipData();                 ClipData.Item item = cd.getItemAt(0);                 String resp = item.coerceToText(context).toString();                  //view dragged item is being dropped on                 ImageView dropTarget = (ImageView) v;                  //view being dragged and dropped                 final ImageView dropped = (ImageView) view;                  dropped.setEnabled(false);                  //if an item has already been dropped here, there will be a tag                 final Object tag = dropTarget.getTag();                  LayoutInflater li = LayoutInflater.from(context);                 View promptsView = li.inflate(R.layout.ns_scoop_dialog, null);                  AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(                         context);                  // set prompts.xml to alertdialog builder                 alertDialogBuilder.setView(promptsView);                  final EditText userInput = (EditText) promptsView                         .findViewById(R.id.edit1);                  // set dialog message                 alertDialogBuilder                         .setIcon(R.mipmap.ic_launcher)                         .setTitle(dropped.getTag().toString())                         .setCancelable(false)                         .setPositiveButton("OK",                                 new DialogInterface.OnClickListener() {                                     public void onClick(DialogInterface dialog,int id) {                                         // get user input and set it to result                                         // edit text                                         String inAmt = userInput.getText().toString();                                          CreateSmoothie.nsList.add(inAmt + " Green Scoops " + dropped.getTag().toString());                                         Log.d(TAG, inAmt + " Green Scoops " + dropped.getTag().toString() + " added to list");                                          dialog.dismiss();                                          //dropped.setEnabled(true);                                     }                                 })                         .setNegativeButton("Cancel",                                 new DialogInterface.OnClickListener() {                                     public void onClick(DialogInterface dialog, int id) {                                         dialog.cancel();                                          int existingID = dropped.getId();                                          //set the original view visible again                                         ((Activity) context).findViewById(existingID).setVisibility(View.VISIBLE);                                          dropped.setEnabled(true);                                      }                                 });                  // create alert dialog                 AlertDialog alertDialog = alertDialogBuilder.create();                  // show it                 alertDialog.show();                 //Button nButton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);                 //nButton.setBackgroundColor(Color.GREEN);                 //Button pButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);                 //pButton.setBackgroundColor(Color.GREEN);                  if(tag!=null)                 {                     //the tag is the view id already dropped here                     int existingID = (Integer)tag;                      //set the original view visible again                     ((Activity) context).findViewById(existingID).setVisibility(View.VISIBLE);                 }                  break;             case DragEvent.ACTION_DRAG_ENDED:                  if(DEBUG) Log.i("drag event", "ended::" + ChoiceTouchListener.offsetX + "," + ChoiceTouchListener.offsetY);                  /**                  * returning false so that goes to parentView onDrag function                  */                 return false;             //break;             default:                 break;         }         return true;     }  } 

Hope that helps.

Read More

Tuesday, February 28, 2017

How to put views on top of an ImageView, in relation to the ImageView's content size?

Leave a Comment

Background

Suppose I want to show an image of the something using an ImageView, and I want to put new views on top of it (animated ImageViews that show pins on a world map image, for example, or a Switch view on top of a smartphone image).

This means that no matter how the ImageView shows the image, the views should be in it, inside correct spot, with the same size as specified, or in a size related to the imageView itself

The problem

As opposed to other views, the ImageView can have a certain size, but its content is something else (to keep aspect ratio).

What I tried

I tried to use ConstraintLayout, but this can't really help, because the ImageView can change its size (for example when changing orientation), and thus ruining the position I've given the views compared to the ImageView.

I've found some libraries that can handle a similar thing (like here) and I even asked a similar question before (here), but all those solutions are for a static image within the ImageView, yet what I search for is adding a view on top of an ImageView.

The question

How do I put the views on top of the ImageView's content correctly?

How do I also scale the views down/up compared to the size of the ImageView's content ?

Can ConstraintLayout be used to change the scale of the views according to the ImageView's size ?

7 Answers

Answers 1

Make FrameLayout with wrap_content around ImageView. Then you could set SwitchView on top of ImageView. You could align it to center, side or corners and using margins to get some fine position.

It still won't scale with image, but you can get pretty good results. If that doesn't fit you, you can programatically get width/height of ImageView and alter position (or margins) of SwitchView accordingly.

Answers 2

With below you can manage width of switch or any other view as per image view width

android:layout_alignLeft="@+id/imageView" android:layout_alignRight="@+id/imageView" 

<Switch     android:id="@+id/swi"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:layout_alignLeft="@+id/imageView"     android:layout_alignRight="@+id/imageView" />  <ImageView     android:id="@+id/imageView"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:layout_below="@+id/swi"     android:src="@drawable/download" /> 

Answers 3

In Java,

        ImageView imgView = (ImageView) findViewById(R.id.imageView);         imageView.setBackgroundResource(R.drawable.yourDrawable);         int width = imgView.getDrawable().getIntrinsicWidth();          Switch switchKey = (Switch) findViewById(R.id.switchKey);         switchKey.setMinimumWidth(width); 

And in XML, align it with alignLeft and alignRight with ImageView.

Answers 4

As far as i get it, you need the image size displayed inside the image view and set that as the max width of your switch view right?

You need both Java and XML for this,

The XML file is basically as RelativeLayout with the view stacked as needed.

   <RelativeLayout         android:layout_width="wrap_content"         android:layout_height="wrap_content">         <ImageView             android:src="@drawable/nonet_icon"             android:id="@+id/iconView"             android:layout_width="wrap_content"             android:layout_height="wrap_content" />         <android.support.v7.widget.SwitchCompat             android:layout_width="wrap_content"             android:visibility="gone"             android:layout_centerInParent="true"             android:layout_height="wrap_content"             android:id="@+id/switchView"/>     </RelativeLayout> 

And the Java Code gets the imageWidth and sets it to the SwitchView.

        mSwitchCompat.setVisibility(View.VISIBLE); //        20% x 25% of Content in ImageView         final float x = mImageView.getDrawable().getIntrinsicWidth()*.2f;         final float y = mImageView.getDrawable().getIntrinsicHeight()*.25f; //        waiting for the view to be drawn         mSwitchCompat.post(new Runnable() {             @Override             public void run() { //        scale current view W.r.t. x and y values               mSwitchCompat.setScaleX((float)mSwitchCompat.getWidth()/x);                 mSwitchCompat.setScaleY((float)mSwitchCompat.getHeight()/y);             }         });         RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,                 WindowManager.LayoutParams.WRAP_CONTENT); //        30% x 35% of content, for location         int xMargin  = Math.round(mImageView.getDrawable().getIntrinsicWidth()*.3f);         int yMargin = Math.round(mImageView.getDrawable().getIntrinsicHeight()*.35f); //      set margin values, can optionally add for top and bottom         layoutParams.setMargins(xMargin,0,yMargin,0);         mSwitchCompat.setLayoutParams(layoutParams); 

Ref: Getting Displayed image size of an ImageView Trying to get the display size of an image in an ImageView

Ref: Dynamic size values

Do comment if you need a detailed explaination.

Example: Check this image!

Scaled View on Image: Scaled View on Image!

Answers 5

You can use MarginLayoutParams with Relative Layout to set left and top position in ImageView.

    image = (ImageView) findViewById(R.id.imageID);     MarginLayoutParams marginParams = new MarginLayoutParams(image.getLayoutParams());     marginParams.setMargins(left_margin, top_margin, right_margin, bottom_margin);     RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);     image.setLayoutParams(layoutParams); 

find complete information for this in below link :

MarginLayoutParams

Answers 6

Try this, may be it will help you.

<RelativeLayout     android:layout_width="wrap_content"     android:layout_height="wrap_content">      <ImageView         android:id="@+id/img_background"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:scaleType="centerCrop"/>      <RelativeLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:background="@color/semi_transparent"         android:layout_margin="@dimen/spacing_small"         android:layout_alignTop="@+id/img_background"         android:layout_alignBottom="@id/img_background">          //this layout will expand according to your image size      </RelativeLayout>  </RelativeLayout> 

Answers 7

Do you want to show switch that lay on imageview ?

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/ll_download"     android:layout_width="100dp"     android:layout_height="60dp"     android:layout_centerInParent="true"     android:orientation="vertical">      <ImageView         android:src="@android:drawable/btn_star_big_on"         android:layout_width="match_parent"         android:layout_height="match_parent" />     <Switch         android:id="@+id/mySwitch"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:text="Switch" /> </RelativeLayout> 

enter image description here

Read More

Sunday, June 19, 2016

Image uri doesn't display images on ImageView on some android device

Leave a Comment

I have an ImageView. When you click on a ImageView, it will open gallery and you pick up a image and show it on ImageView. I have a condition that when I close my app and then I open it, the image will retain there . So for that, I am storing image Uri on sharedprefrence. And on opening the application i am retrieving the same Uri and tries to display the image on imageView.

However in some phones - image appears perfect like Mi(Lollipop), Samsung(KitKat) but it doesn't appear in phones like - Motorola(Marshmallow) ,One Plus One (Marshmallow). Any idea why it's happening ? Here is my code

For picking up an image i am using

Intent intent=new Intent();intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), Constants.SELECT_PICTURE); 

And on OnActivityResult() code is

 @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {      super.onActivityResult(requestCode, resultCode, data);       if(requestCode==Constants.SELECT_PICTURE && resultCode==RESULT_OK && null!=data) {          Uri uri=data.getData();          Picasso.with(UsersProfileActivity.this)              .load(uri)              .centerCrop()              .resize(200,200)              .into(img_photo);           // This profile image i am storing into a sharedpreference                  profile_image=uri.toString();      } 

And while retrieving from sharedprefrence I convert String to uri by using Uri.parse(profile_image)

However if I notice, uri returns for different android phone is as follows

Mi(Lollipop)- Uri=content://media/external/images/media/12415 samsung(KitKat)-Uri=content://media/external/images/media/786 Motorola(Marshmallow)- Uri=content://com.android.providers.media.documents/document/image%3A30731 One Plus One (Marshmallow)- Uri=content://com.android.providers.media.documents/document/image%3A475 

Hence when uri content is -content://media/external/images/media/ is display image on ImageView Perfect and in other cases it is not

10 Answers

Answers 1

Try this

I developed and tested and working on

  1. Lenovo K3 Note(Marshmallow)
  2. Motorola(Lollipop)
  3. Samsung(KitKat)

In your MainActivity.java add

    profilePicture = (ImageView)findViewById(R.id.imgProfilePicture);     sharedPreferences = getSharedPreferences(getString(R.string.app_name)+"_ProfileDetails",MODE_PRIVATE);      // get uri from shared preference     String profilePicUri = sharedPreferences.getString("profilePicUrl","");      // if uri not found     if (profilePicUri.equalsIgnoreCase("")){         // code for open gallery to select image         Intent intent;         if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){             intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);             intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);             intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);         }else{             intent = new Intent(Intent.ACTION_GET_CONTENT);         }         intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);         intent.setType("image/*");          startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE_CONSTANT);     }else{         try{             final int takeFlags =  (Intent.FLAG_GRANT_READ_URI_PERMISSION                     | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);             // Check for the freshest data.             getContentResolver().takePersistableUriPermission(Uri.parse(profilePicUri), takeFlags);             // convert uri to bitmap             Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.parse(profilePicUri));             // set bitmap to imageview             profilePicture.setImageBitmap(bitmap);         }         catch (Exception e){             //handle exception             e.printStackTrace();         }     } 

Now Handle onActivityResult.

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {     super.onActivityResult(requestCode, resultCode, data);     if (requestCode == SELECT_PICTURE_CONSTANT && resultCode == RESULT_OK && null != data) {         Uri uri = data.getData();         // This profile image i am storing into a sharedpreference         SharedPreferences.Editor editor = sharedPreferences.edit();         // save uri to shared preference         editor.putString("profilePicUrl",uri.toString());         editor.commit();         profilePicture.setImageURI(uri);     } } 

In your Manifest file add permission

<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

Note:

Assuming you added code for take permission for Marshmallow

Result Uri

lenovo K3 Note: content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FIMG_20160606_212815.jpg

samsung: content://com.android.providers.media.documents/document/image%3A2086

motorola: content://com.android.providers.media.documents/document/image%3A15828

Answers 2

You need to request the permission to read external storage to user at runtime for Android 6+

https://developer.android.com/training/permissions/requesting.html#perm-check

Hope this helps.

Answers 3

Maybe you can handle it by converting URI to real path first.

public String getRealPathFromURI(Context context, Uri contentUri) {     Cursor cursor = null;     try {         String[] proj = { MediaStore.Images.Media.DATA };         cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);         int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);         cursor.moveToFirst();         return cursor.getString(column_index);     } finally {         if (cursor != null) {             cursor.close();         }     } } 

And your onActivityResult should looks like this

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {     super.onActivityResult(requestCode, resultCode, data);      if(requestCode==Constants.SELECT_PICTURE && resultCode==RESULT_OK && null!=data)     {         Uri uri=data.getData();         String imagePath = getRealPathFromURI(getApplicationContext(), uril);  Picasso.with(UsersProfileActivity.this).load(imagePath).centerCrop().resize(200,200).into(img_photo);       profile_image = imagePath;        } 

Answers 4

I have managed to do this in the past. Instead of storing it in SharePreferences, I save it in the Bundle when onSaveInstanceState(Bundle) get called by: bundle.putParcelable(SOME_KEY, uri). You can do this because Uri implements Parcelable. After that, check for this uri in the Bundle passed in onCreate(). Code:

public void onCreate(Bundle savedInstanceState){     super.onCreate(savedInstanceState);     if (savedInstanceState != null){         loadImage((Uri)saveInstanceState.getParcelable(SOME_KEY))     } }  public void onSaveInstanceState(Bundle bundle){      bundle.putParcelable(SOME_KEY, uri) } 

P/S: I guess the problem of storing the uri in SharePreference is encoding/decoding Uri.

Answers 5

Quoting from 4.4 API overview:

'On previous versions of Android, if you want your app to retrieve a specific type of file from another app, it must invoke an intent with the ACTION_GET_CONTENT action. This action is still the appropriate way to request a file that you want to import into your app. However, Android 4.4 introduces the ACTION_OPEN_DOCUMENT action, which allows the user to select a file of a specific type and grant your app long-term read access to that file (possibly with write access) without importing the file to your app.'(emphasis added)

To allow your app to retrieve previously-selected images, just change the action from ACTION_GET_CONTENT to ACTION_OPEN_DOCUMENT (solution confirmed working on Nexus 7 2013).

    Intent intent = new Intent();     intent.setType("image/*");     String action = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? Intent.ACTION_OPEN_DOCUMENT : Intent.ACTION_GET_CONTENT;     intent.setAction(action);     startActivityForResult(Intent.createChooser(intent, "Select Picture"), Constants.SELECT_PICTURE); 

Answers 6

You can Easily convert URI to Bitmap:

ParcelFileDescriptor parcelFileDescriptor =                 context.getContentResolver().openFileDescriptor(selectedFileUri, "r");         FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();         Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);           parcelFileDescriptor.close(); 

And then set in to Imageview: imgview.setImageBitmap(image);

Hope this will help you.

Answers 7

Could be a Picasso versioning issue. They fixed something with loading large images in version 2.5.0 (2.4.0...?), which isn't available via the repositories yet.

You'll need to manually include the nightly snapshot of Picasso, and that will likely fix your issue. It did for me.

Answers 8

Pass your URI in this method it will return a String and than convert it into Bitmap

  String path = getPath(getApplicationContext(), uri);   Bitmap bitmap = BitmapFactory.decodeFile(path);   imageView.setImageBitmap(bitmap);       public static String getPath(final Context context, final Uri uri) {      // DocumentProvider     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {          if (isExternalStorageDocument(uri)) {// ExternalStorageProvider             final String docId = DocumentsContract.getDocumentId(uri);             final String[] split = docId.split(":");             final String type = split[0];             String storageDefinition;               if ("primary".equalsIgnoreCase(type)) {                  return Environment.getExternalStorageDirectory() + "/" + split[1];              } else {                  if (Environment.isExternalStorageRemovable()) {                     storageDefinition = "EXTERNAL_STORAGE";                  } else {                     storageDefinition = "SECONDARY_STORAGE";                 }                  return System.getenv(storageDefinition) + "/" + split[1];             }          } else if (isDownloadsDocument(uri)) {// DownloadsProvider              final String id = DocumentsContract.getDocumentId(uri);             final Uri contentUri = ContentUris.withAppendedId(                     Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));              return getDataColumn(context, contentUri, null, null);          } else if (isMediaDocument(uri)) {// MediaProvider             final String docId = DocumentsContract.getDocumentId(uri);             final String[] split = docId.split(":");             final String type = split[0];              Uri contentUri = null;             if ("image".equals(type)) {                 contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;             } else if ("video".equals(type)) {                 contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;             } else if ("audio".equals(type)) {                 contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;             }              final String selection = "_id=?";             final String[] selectionArgs = new String[]{                     split[1]             };              return getDataColumn(context, contentUri, selection, selectionArgs);         }      } else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore (and general)          // Return the remote address         if (isGooglePhotosUri(uri))             return uri.getLastPathSegment();          return getDataColumn(context, uri, null, null);      } else if ("file".equalsIgnoreCase(uri.getScheme())) {// File         return uri.getPath();     }      return null; } 

Answers 9

I also run into something like this earlier and found a useful helper class which gives you the file's exact location. Here is the link.

You can use the methods like FileUtils.getPath(context, uri) or FileUtils.getFile(context, uri) to get the file. Then just use it like this:

 Picasso.with(UsersProfileActivity.this)          .load(Uri.fromFile(file))          .centerCrop()          .resize(200,200)          .into(img_photo); 

Hope this helps.

Answers 10

Just not 100% sure if I get the question. If certain images cannot be shown in the imageView (even before closing and restarting the app) then the issue is with Picasso is being able to handle the contents from certain providers. I am not getting the sense that this is the case, but if it is, then you might want to consider filing a bug/RFE for that library. On the other hand, if Picasso is correctly showing the image for a given Uri, but not after Uri_org -> String -> Uri_regen conversion then it means that Uri_org is not the same as Uri_regen. You can (temporarily) add a couple of lines your code to convert the String back to Uri and put a breakpoint just after and compare the two Uri's. That should give you a clue as to how things are going wrong.

profile_image=uri.toString(); //add the next few lines for debugging purposes only; remove them later Uri uri2 = Uri.parse(profile_image) if (!uri.equals(uri2)    //add a breakpoint on the next line    Log.d("Uri mismatch), "Ouch"); //remove the lines after you are done with debugging 

If you are not hitting the breakpoint, then move the breakpoint back to the "if" statement and visually check the two Uri's (which almost certainly will be the same, otherwise you would have had hit the breakpoint, but this would help checking the debug code itself). If the Uri's are the same then somehow the String preference is not being preserved correctly for some reason. In that case make a note of the original Uri and add a breakpoint on the line that converts the String back to Uri:

Uri uri = Uri.parse(profile_image) //profile_image is retrieved from sharedpreferences 

If the previous experiment worked, it should be working again here unless the profile_image is different. Either way you should get pointers as to where the issue is.

Good luck!

Read More

Sunday, June 12, 2016

Erasing a rotated image in Android does not show erase the correct path

Leave a Comment

We are building an Android application that involves image editing. A few of the features include rotating an image and erasing part of the image.

We are using the following library: https://github.com/nimengbo/StickerView

We have successfully created a function to rotate and erase the image. However, when we tried to perform the following actions:

  1. Rotating an image at a certain degree.
  2. Then, erasing the image.

We found the following bug:

  1. When we tried to erase the rotated image, the erased path did not reflect the path which our finger traced on the screen.

enter image description here

From the above image, the yellow line is the actual movement of the finger (straight down vertical across the sticker). But, the resulting erased path was found to be diagonal.

This problem only exists when the image is rotated. It does not exist when the image is not rotated.

After further debugging, we have a few assumptions from the above problems:

  1. Due to the rotated image, the x and y absolution position is changed. Thus, the path does not reflect the correct path by the touch routes.

How can we ensure that the path is still referencing the right path on what the finger is touching even after being rotated?

Here is the code we have in our StickerView.java class that extends ImageView class.

onTouchEvent

@Override public boolean onTouchEvent(MotionEvent event) {     int action = MotionEventCompat.getActionMasked(event);      float[] pointXY = new float[2];      pointXY = getAbsolutePosition(event.getX(0),event.getY(0));     float xPoint = pointXY[0];     float yPoint = pointXY[1];       switch (action) {         case MotionEvent.ACTION_DOWN:              // first touch             // if it is inside the image             if (isInBitmap(event)) {                 // set isInSide to true                 isInSide = true;                  // if it is a scratch                 if(doScratch){                     // start creating the scratch path                     mScratchPath = new Path();                     mScratchPath.moveTo(xPoint, yPoint);                     mScratchPath.lineTo(xPoint, yPoint);                     paths.add(new Pair<Path, Paint>(mScratchPath, mScratchCurrentPaint));                 }             }             break;         case MotionEvent.ACTION_MOVE:              // if two fingers touch and is not a scratch,             // then it means we can rotate / resize / pan             if (isPointerDown && !doScratch) {                 // reset matrix                 matrix.reset();                 // get the center point                 scaledImageCenterX = (mImageWidth * mScaleFactor) / 2 ;                 scaledImageCenterY = (mImageHeight * mScaleFactor) / 2;                  // ROTATE THE IMAGE !!!                 matrix.postRotate(lastRotateDegree, scaledImageCenterX, scaledImageCenterY);                  // done to call onDraw                 invalidate();             }             break;     }      if (operationListener != null) {         operationListener.onEdit(this);     }      // if it is a scratch     if(doScratch){         // then for every point, create a scratch path         mScratchPath.lineTo(xPoint, yPoint);         invalidate();     }else{         mScaleDetector.onTouchEvent(event);         mRotateDetector.onTouchEvent(event);         mMoveDetector.onTouchEvent(event);         mShoveDetector.onTouchEvent(event);     }     return handled; } 

onDraw

@Override protected void onDraw(Canvas canvas) {     super.onDraw(canvas);      // if the image exists     if (mBitmap != null) {         // save canvas         canvas.save();          // if it is a scratch         if(doScratch){             // scratch the image             mFillCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);              // Draw our surface, nice an pristine             final Drawable surface = mScratchSurface;             if(surface != null) {                 surface.draw(mFillCanvas);             }             //Scratch the surface             if(paths != null) {                 for (Pair<Path, Paint> p : paths) {                     mFillCanvas.drawPath(p.first,p.second);                 }             }             mBitmap = mFillCache;         }          canvas.drawBitmap(mBitmap, matrix, bitmapPaint);         canvas.restore();     } } 

getAbsolutePosition function

public float[] getAbsolutePosition(float Ax, float Ay) {    float[] mMatrixValues = new float[9];    matrix.getValues(mMatrixValues);     float x = mImageWidth - ((mMatrixValues[Matrix.MTRANS_X] - Ax) / mMatrixValues[Matrix.MSCALE_X]) - (mImageWidth - getTranslationX());     float y = mImageHeight - ((mMatrixValues[Matrix.MTRANS_Y] - Ay) / mMatrixValues[Matrix.MSCALE_X]) - (mImageHeight - getTranslationY());     return new float[] { x, y}; } 

2 Answers

Answers 1

You need to apply the rotation matrics on your coordinates. Here theta is the angle by which the image is rotated. You Need to Apply Matrix rotation

Image source wikipedia

In code it will be something like this

int getAbsoluteX(int x, int y, double theta) {    int x_new = (int)(x*Math.cos(theta) - y*Math.sin(theta));    return x_new; }  int getAbsoluteY(int x, int y, double theta)  {    int y_new = (int)(x*Math.sin(theta) + y*Math.cos(theta));    return y_new; } 

Answers 2

You are rotating the entire view in the onDraw method. Not only this affects the performance (you are repeating the same transformation every time), it affects the outcome as you noticed since it rotates everything in the view, including the paths.

If for some reason you must do it this way (not recommended), then you need to rotate the paths in the opposite direction by the same amount. I strongly suggest you don't do that. Try to find a way around rotating the background inside the onDraw, instead. For example, whenever the background is rotated, you can create a new background (outside the onDraw method) and use that background in the onDraw method.

Read More