Android set image from URI on ImageView -


updated more code

i trying grab picture taken , set imageview programmatically.

the picture button pressed,

picture_button.setonclicklistener(new view.onclicklistener() {     public void onclick(view v) {         takephoto(mtextureview);     } }); 

it runs takephoto method:

public void takephoto(view view) {     try {         mimagefile = createimagefile();         final imageview latest_picture = (imageview) findviewbyid(r.id.latest_picture);         final relativelayout latest_picture_container = (relativelayout) findviewbyid(r.id.latest_picture_container);         final string mimagefilelocationnew = mimagefilelocation.replacefirst("^/", "");         toast.maketext(getapplicationcontext(), "" + mimagefile, toast.length_short).show();         uri uri = uri.fromfile(mimagefile);         toast.maketext(getapplicationcontext(), ""+uri, toast.length_long).show();         latest_picture.setimageuri(uri);         latest_picture_container.setvisibility(view.visible);     } catch (ioexception e){         e.printstacktrace();     }     lockfocus();     capturestillimage(); } 

which runs createimagefile() , capturestillimage()

private void capturestillimage() {     try {         capturerequest.builder capturestillbuilder = mcameradevice.createcapturerequest(cameradevice.template_still_capture);         capturestillbuilder.addtarget(mimagereader.getsurface());         int rotation = getwindowmanager().getdefaultdisplay().getrotation();         capturestillbuilder.set(capturerequest.jpeg_orientation, orientations.get(rotation));         cameracapturesession.capturecallback capturecallback = new cameracapturesession.capturecallback() {             @override             public void oncapturecompleted(cameracapturesession session, capturerequest request, totalcaptureresult result) {                 super.oncapturecompleted(session, request, result);                 //toast.maketext(getapplicationcontext(), "image taken", toast.length_short).show();                 unlockfocus();             }         };         mcameracapturesession.capture(capturestillbuilder.build(), capturecallback, null);     } catch (cameraaccessexception e) {         e.printstacktrace();     } }  file createimagefile() throws ioexception {     string timestamp = new simpledateformat("yyyymmdd").format(new date());     string subfolder = "";     if(pref_session_unique_gallery.equals("yes")){         if(event_name != null){             subfolder = event_name;         } else {             subfolder = timestamp;         }     } else {         subfolder = "_gen";     }     if(event_name == null){         event_name = "";     } else {         event_name = event_name + "_";     }     string imagefilename = "cpb_"+event_name+timestamp+"_";     file storagedirectory = new file(environment.getexternalstoragedirectory() + file.separator + "cpb" + file.separator + subfolder);     storagedirectory.mkdir();     file image = file.createtempfile(imagefilename, ".jpg", storagedirectory);     mimagefilelocation = image.getabsolutepath();     return image; } 

and image saved here:

private static class imagesaver implements runnable {     private final image mimage;     private imagesaver(image image) {         mimage = image;     }     @override     public void run() {         bytebuffer bytebuffer = mimage.getplanes()[0].getbuffer();         byte[] bytes = new byte[bytebuffer.remaining()];         bytebuffer.get(bytes);          fileoutputstream fileoutputstream = null;          try {             fileoutputstream = new fileoutputstream(mimagefile);             fileoutputstream.write(bytes);          } catch (ioexception e) {             e.printstacktrace();         } {             mimage.close();             if(fileoutputstream != null){                 try {                     fileoutputstream.close();                 } catch (ioexception e) {                     e.printstacktrace();                 }              }         } 

i getting correct path image after createimagefile() , toasting show every time. not setvisibility on latest_picture_container working... if comment out inputstream, bitmap , setimagebitmap, latest_picture_container shows normal. not sure why wrong.

for reason, uri coming 3 slashes after file,

file:///storage/0/... 

the assetmanager#open() method works app's assets; i.e., files in project's /assets folder. since you're trying open external file, should instead use fileinputstream on file object created path. additionally, takephoto() method setting image on imageview before has been written file, result in empty imageview.

since app using camera directly, can decode image same byte array being written image file, , save ourselves unnecessary storage read. furthermore, in example code follows, file write happening on separate thread, might take advantage of in performing image decode, minimize impact on ui thread.

first we'll create interface through imagesaver can pass image activity display in imageview.

public interface onimagedecodedlistener {     public void onimagedecoded(bitmap b); } 

then we'll need alter imagesaver class bit take activity parameter in constructor. i've added file parameter, activity's corresponding field need not static.

private static class imagesaver implements runnable {     private final activity mactivity;     private final image mimage;     private final file mimagefile;      public imagesaver(activity activity, image image, file imagefile) {         mactivity = activity;         mimage = image;         mimagefile = imagefile;     }      @override     public void run() {         bytebuffer bytebuffer = mimage.getplanes()[0].getbuffer();         byte[] bytes = new byte[bytebuffer.remaining()];         bytebuffer.get(bytes);          final bitmap b = bitmapfactory.decodebytearray(bytes, 0, bytes.length);         mactivity.runonuithread(new runnable() {                 @override                 public void run() {                     ((onimagedecodedlistener) mactivity).onimagedecoded(b);                 }             }         );          fileoutputstream fileoutputstream = null;         ...     } } 

as image data in byte array, decode , pass activity, doesn't have wait on file write, can proceed quietly in background. need invoke interface method on ui thread, since we're "touching" views there.

the activity need implement interface, , can move view-related stuff takephoto() onimagedecoded() method.

public class mainactivity extends activity     implements imagesaver.onimagedecodedlistener {     ...      @override     public void onimagedecoded(bitmap b) {         final imageview latest_picture =             (imageview) findviewbyid(r.id.latest_picture);         final relativelayout latest_picture_container =             (relativelayout) findviewbyid(r.id.latest_picture_container);          latest_picture.setimagebitmap(b);         latest_picture_container.setvisibility(view.visible);     }      public void takephoto(view view) {         try {             mimagefile = createimagefile();             capturestillimage();             lockfocus();         }         catch (ioexception e) {             e.printstacktrace();         }     }     ... } 

finally, need execute imagesaver in imagereader's onimageavailable() method. again following example, this.

private final imagereader.onimageavailablelistener monimageavailablelistener =      new imagereader.onimageavailablelistener() {     @override     public void onimageavailable(imagereader reader) {         mbackgroundhandler.post(new imagesaver(mainactivity.this,                                                reader.acquirenextimage(),                                                mimagefile)         );     } }; 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -