how to generate thumbnail of recently taken video from camera in android using camera2 API? -
mainactivity.java
(this main class functionalities), need generate thumbnail of videos on corner of camera app & when thumbnail clicked play video.
i have tried recycler view didnt worked. can me out ?
import android.manifest; import android.annotation.targetapi; import android.content.context; import android.content.intent; import android.content.pm.packagemanager; import android.graphics.bitmap; import android.graphics.surfacetexture; import android.hardware.camera2.cameraaccessexception; import android.hardware.camera2.cameracapturesession; import android.hardware.camera2.cameracharacteristics; import android.hardware.camera2.cameradevice; import android.hardware.camera2.cameramanager; import android.hardware.camera2.capturerequest; import android.hardware.camera2.params.streamconfigurationmap; import android.media.mediarecorder; import android.media.thumbnailutils; import android.net.uri; import android.os.build; import android.os.bundle; import android.os.environment; import android.os.handler; import android.os.handlerthread; import android.os.systemclock; import android.provider.mediastore; import android.support.v4.content.contextcompat; import android.support.v7.app.appcompatactivity; import android.util.size; import android.util.sparseintarray; import android.view.surface; import android.view.textureview; import android.view.view; import android.widget.chronometer; import android.widget.imagebutton; import android.widget.imageview; import android.widget.toast; import java.io.file; import java.io.ioexception; import java.text.simpledateformat; import java.util.arraylist; import java.util.arrays; import java.util.collections; import java.util.comparator; import java.util.date; import java.util.list; @targetapi(build.version_codes.lollipop) public class mainactivity extends appcompatactivity { public static final int request_camera_permission_result = 0; public static final int request_write_external_storage_permission_result = 1; private textureview mtextureview; private textureview.surfacetexturelistener msurfacetexturelistener = new textureview.surfacetexturelistener() { @override public void onsurfacetextureavailable(surfacetexture surfacetexture, int width, int height) { //toast.maketext(getapplicationcontext(),"textureview available",toast.length_short).show(); setupcamera(width, height); connectcamera(); } @override public void onsurfacetexturesizechanged(surfacetexture surfacetexture, int width, int height) { } @override public boolean onsurfacetexturedestroyed(surfacetexture surfacetexture) { return false; } @override public void onsurfacetextureupdated(surfacetexture surfacetexture) { } }; private cameradevice mcameradevice; private cameradevice.statecallback mcameradevicestatecallback = new cameradevice.statecallback() { @override public void onopened(cameradevice camera) { mcameradevice = camera; if(misrecording){ try { createvideofilename(); } catch (ioexception e) { e.printstacktrace(); } startrecord(); mmediarecorder.start(); mchronometer.setbase(systemclock.elapsedrealtime()); mchronometer.setvisibility(view.visible); mchronometer.start(); }else{ startpreview(); } //toast.maketext(getapplicationcontext(),"camera connected",toast.length_short).show(); } @override public void ondisconnected(cameradevice camera) { camera.close(); mcameradevice = null; bitmap thumb = thumbnailutils.createvideothumbnail(mvideofilename ,mediastore.images.thumbnails.mini_kind); imageview myimage = (imageview) findviewbyid(r.id.thumbnail); myimage.setimagebitmap(thumb); } @override public void onerror(cameradevice camera, int i) { } }; private handlerthread mbackgroundhandlerthread; private handler mbackgroundhandler; private string mcameraid; private size mpreviewsize; private size mvideosize; private mediarecorder mmediarecorder; private chronometer mchronometer; private int mtotalrotation; private capturerequest.builder mcapturerequestbuilder; private imagebutton mrecordimagebutton; private boolean misrecording = false; private file mvideofolder; private string mvideofilename; //private static file mrawvideofilename; private static sparseintarray orientations = new sparseintarray(); static { orientations.append(surface.rotation_0, 0); orientations.append(surface.rotation_90, 90); orientations.append(surface.rotation_180, 180); orientations.append(surface.rotation_270, 270); } private static class comparesizebyarea implements comparator<size> { @override public int compare(size lhs, size rhs) { return long.signum((long) lhs.getwidth() * lhs.getheight() / (long) rhs.getwidth() * rhs.getheight()); } } // public static boolean contains(int[] modes, int mode){ // if (modes == null){ // return false; // } // for(int : modes){ // if(i == mode){ // return true; // } // } // return false; // } @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); createvideofolder(); mmediarecorder = new mediarecorder(); mchronometer = (chronometer) findviewbyid(r.id.chronometer); mtextureview = (textureview) findviewbyid(r.id.textureview); final bitmap thumb = thumbnailutils.createvideothumbnail(mvideofilename, mediastore.images.thumbnails.mini_kind); mrecordimagebutton = (imagebutton) findviewbyid(r.id.videobutton); mrecordimagebutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { if (misrecording) { mchronometer.stop(); mchronometer.setvisibility(view.invisible); misrecording = false; mrecordimagebutton.setimageresource(r.mipmap.start_recording); //toast.maketext(getapplicationcontext(),"started",toast.length_short).show(); mmediarecorder.stop(); mmediarecorder.reset(); intent mediastoreupdateintent = new intent(intent.action_media_scanner_scan_file); mediastoreupdateintent.setdata(uri.fromfile(new file(mvideofilename))); sendbroadcast(mediastoreupdateintent); startpreview(); } else { checkwritestoragepermission(); //checkwritestoragepermission(); } } }); } @override protected void onresume() { super.onresume(); startbackgroundthread(); if (mtextureview.isavailable()) { setupcamera(mtextureview.getwidth(), mtextureview.getheight()); connectcamera(); } else { mtextureview.setsurfacetexturelistener(msurfacetexturelistener); } } @override public void onrequestpermissionsresult(int requestcode, string[] permission, int[] grantresults) { super.onrequestpermissionsresult(requestcode, permission, grantresults); if (requestcode == request_camera_permission_result) { if (grantresults[0] != packagemanager.permission_granted) { toast.maketext(getapplicationcontext(), "application not run without camera service", toast.length_short).show(); } if (grantresults[0] != packagemanager.permission_granted) { toast.maketext(getapplicationcontext(), "application not have audio on record ", toast.length_short).show(); } } if (requestcode== request_write_external_storage_permission_result){ if(grantresults[0]== packagemanager.permission_granted){ misrecording=true; mrecordimagebutton.setimageresource(r.mipmap.ic_launcher); try { createvideofilename(); } catch (ioexception e) { e.printstacktrace(); } toast.maketext(this,"permission granted",toast.length_short).show(); }else { toast.maketext(this,"app needs save video run",toast.length_short).show(); } } } @override protected void onpause() { closecamera(); stopbackgroundthread(); super.onpause(); } @override public void onwindowfocuschanged(boolean hasfocus) { super.onwindowfocuschanged(hasfocus); view decorview = getwindow().getdecorview(); if (hasfocus) { decorview.setsystemuivisibility(view.system_ui_flag_layout_stable | view.system_ui_flag_immersive_sticky | view.system_ui_flag_layout_fullscreen | view.system_ui_flag_layout_hide_navigation | view.system_ui_flag_fullscreen | view.system_ui_flag_hide_navigation); } } private void setupcamera(int width, int height) { cameramanager cameramanager = (cameramanager) getsystemservice(context.camera_service); try { (string cameraid : cameramanager.getcameraidlist()) { cameracharacteristics cameracharacteristics = cameramanager.getcameracharacteristics(cameraid); if (cameracharacteristics.get(cameracharacteristics.lens_facing) == cameracharacteristics.lens_facing_back) { continue; } streamconfigurationmap map = cameracharacteristics.get(cameracharacteristics.scaler_stream_configuration_map); int deviceorientation = getwindowmanager().getdefaultdisplay().getrotation(); mtotalrotation = sensortodevicerotation(cameracharacteristics, deviceorientation); boolean swaprotation = mtotalrotation == 90 || mtotalrotation == 270; int rotatewidth = width; int rotateheight = height; if (swaprotation) { rotatewidth = height; rotateheight = width; } mpreviewsize = chooseoptimalsize(map.getoutputsizes(surfacetexture.class), rotatewidth, rotateheight); mvideosize = chooseoptimalsize(map.getoutputsizes(mediarecorder.class), rotatewidth, rotateheight); mcameraid = cameraid; return; } } catch (cameraaccessexception e) { e.printstacktrace(); } } private void connectcamera() { cameramanager cameramanager = (cameramanager) getsystemservice(context.camera_service); try { if (build.version.sdk_int >= build.version_codes.m) { if (contextcompat.checkselfpermission(this, manifest.permission.camera) == packagemanager.permission_granted) { cameramanager.opencamera(mcameraid, mcameradevicestatecallback, mbackgroundhandler); } else { if (shouldshowrequestpermissionrationale(manifest.permission.camera)) { toast.maketext(this, "video app required access camera", toast.length_short).show(); } requestpermissions(new string[]{android.manifest.permission.camera,manifest.permission.record_audio}, request_camera_permission_result); } } else { cameramanager.opencamera(mcameraid, mcameradevicestatecallback, mbackgroundhandler); } } catch (cameraaccessexception e) { e.printstacktrace(); } } private void startrecord(){ try { setupmediarecorder(); surfacetexture surfacetexture = mtextureview.getsurfacetexture(); surfacetexture.setdefaultbuffersize(mpreviewsize.getwidth(),mpreviewsize.getheight()); surface previewsurface = new surface(surfacetexture); surface recordsurface = mmediarecorder.getsurface(); mcapturerequestbuilder = mcameradevice.createcapturerequest(cameradevice.template_record); mcapturerequestbuilder.addtarget(previewsurface); mcapturerequestbuilder.addtarget(recordsurface); mcameradevice.createcapturesession(arrays.aslist(previewsurface,recordsurface),new cameracapturesession.statecallback(){ @override public void onconfigured(cameracapturesession session) { try { session.setrepeatingrequest(mcapturerequestbuilder.build(),null,null); } catch (cameraaccessexception e) { e.printstacktrace(); } } @override public void onconfigurefailed(cameracapturesession session) { } },null); }catch (exception e) { e.printstacktrace(); } } private void startpreview() { surfacetexture surfacetexture = mtextureview.getsurfacetexture(); surfacetexture.setdefaultbuffersize(mpreviewsize.getwidth(), mpreviewsize.getheight()); surface previewsurface = new surface(surfacetexture); try { mcapturerequestbuilder = mcameradevice.createcapturerequest(cameradevice.template_preview); mcapturerequestbuilder.addtarget(previewsurface); mcameradevice.createcapturesession(arrays.aslist(previewsurface), new cameracapturesession.statecallback() { @override public void onconfigured(cameracapturesession session) { try { session.setrepeatingrequest(mcapturerequestbuilder.build(), null, mbackgroundhandler); } catch (cameraaccessexception e) { e.printstacktrace(); } } @override public void onconfigurefailed(cameracapturesession cameracapturesession) { toast.maketext(getapplicationcontext(), "unable setup camera preview", toast.length_short).show(); } }, null); } catch (cameraaccessexception e) { e.printstacktrace(); } } private void closecamera() { if (mcameradevice != null) { mcameradevice.close(); mcameradevice = null; } } private void startbackgroundthread() { mbackgroundhandlerthread = new handlerthread("authortv"); mbackgroundhandlerthread.start(); mbackgroundhandler = new handler(mbackgroundhandlerthread.getlooper()); } private void stopbackgroundthread() { mbackgroundhandlerthread.quitsafely(); try { mbackgroundhandlerthread.join(); mbackgroundhandlerthread = null; mbackgroundhandler = null; } catch (interruptedexception e) { e.printstacktrace(); } } private static int sensortodevicerotation(cameracharacteristics cameracharacteristics, int deviceorientation) { int sensororientation = cameracharacteristics.get(cameracharacteristics.sensor_orientation); deviceorientation = orientations.get(deviceorientation); return (sensororientation + deviceorientation + 360) % 360; } private static size chooseoptimalsize(size[] choices, int width, int height) { list<size> bigenough = new arraylist<size>(); (size option : choices) { if (option.getheight() == option.getwidth() * height / width && option.getwidth() >= width && option.getheight() >= height) { bigenough.add(option); } } if (bigenough.size() > 0) { return collections.min(bigenough, new comparesizebyarea()); } else { return choices[0]; } } private void createvideofolder() { file moviefile = environment.getexternalstoragepublicdirectory(environment.directory_movies); mvideofolder = new file(moviefile, "authortvcam"); if (!mvideofolder.exists()){ mvideofolder.mkdirs(); } } private file createvideofilename() throws ioexception { string timestamp = new simpledateformat("yyyymmdd_hhmmss").format(new date()); string prepend = "video_" + timestamp + "_"; file videofile = file.createtempfile(prepend, ".mp4", mvideofolder); mvideofilename = videofile.getabsolutepath(); return videofile; } // private file createrawvideofilename() throws ioexception { // string timestamp = new simpledateformat("yyyymmdd_hhmmss").format(new date()); // string prepend = "raw_" + timestamp + "_"; // file rawvideofile = file.createtempfile(prepend, ".jpeg", mrawvideofolder); // mvideofilename = rawvideofile.getabsolutepath(); // return rawvideofile; // } private void checkwritestoragepermission() { if (build.version.sdk_int >= build.version_codes.m) { if (contextcompat.checkselfpermission(this, manifest.permission.write_external_storage) == packagemanager.permission_granted) { misrecording = true; mrecordimagebutton.setimageresource(r.mipmap.stop_recording); try { createvideofilename(); } catch (ioexception e) { e.printstacktrace(); } startrecord(); mmediarecorder.start(); mchronometer.setbase(systemclock.elapsedrealtime()); mchronometer.setvisibility(view.visible); mchronometer.start(); } else { if (shouldshowrequestpermissionrationale(manifest.permission.write_external_storage)) { toast.maketext(this, "app needs able save videos", toast.length_short).show(); } requestpermissions(new string[]{manifest.permission.write_external_storage}, request_write_external_storage_permission_result); } } else { misrecording = true; mrecordimagebutton.setimageresource(r.mipmap.stop_recording); try { createvideofilename(); } catch (ioexception e) { e.printstacktrace(); } startrecord(); mmediarecorder.start(); mchronometer.setbase(systemclock.elapsedrealtime()); mchronometer.setvisibility(view.visible); mchronometer.start(); } } private void setupmediarecorder()throws ioexception{ mmediarecorder.setvideosource(mediarecorder.videosource.surface); mmediarecorder.setaudiosource(mediarecorder.audiosource.mic); mmediarecorder.setoutputformat(mediarecorder.outputformat.mpeg_4); mmediarecorder.setoutputfile(mvideofilename); mmediarecorder.setvideoencodingbitrate(1000000); mmediarecorder.setvideoframerate(30); mmediarecorder.setvideosize(mvideosize.getwidth(),mvideosize.getheight()); mmediarecorder.setvideoencoder(mediarecorder.videoencoder.h264); mmediarecorder.setaudioencoder(mediarecorder.audioencoder.aac); mmediarecorder.setorientationhint(mtotalrotation); mmediarecorder.prepare(); } }
activity.xml
i not able view thumbnail on camera display screen.i have attached xml file can @aahmed check problem.
<?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingtop="70dp" android:paddingbottom="50dp" tools:context=".mainactivity"> <imageview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/thumbnail" android:layout_alignleft="@+id/chronometer" android:layout_alignstart="@+id/chronometer" /> <textureview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textureview" android:layout_alignparentstart="true" /> <imagebutton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/videobutton" android:src="@mipmap/start_recording" android:contentdescription="@string/video_button" android:layout_alignparentbottom="true" android:layout_centerhorizontal="true" android:layout_marginbottom="39dp" /> <chronometer android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/chronometer" android:visibility="invisible" android:textcolor="#ff0000" android:textsize="25dp" android:layout_centerhorizontal="true" /> </relativelayout>
have tried below code,
bitmap thumb = thumbnailutils.createvideothumbnail(path,mediastore.images.thumbnails.mini_kind);
update
private cameradevice.statecallback mcameradevicestatecallback = new cameradevice.statecallback() { @override public void onopened(cameradevice camera) { mcameradevice = camera; if(misrecording){ try { createvideofilename(); } catch (ioexception e) { e.printstacktrace(); } startrecord(); mmediarecorder.start(); mchronometer.setbase(systemclock.elapsedrealtime()); mchronometer.setvisibility(view.visible); mchronometer.start(); }else{ startpreview(); } //toast.maketext(getapplicationcontext(),"camera connected",toast.length_short).show(); } @override public void ondisconnected(cameradevice camera) { camera.close(); mcameradevice = null; //here camera disconnected, so, can other ui stuffs here. bitmap thumb = thumbnailutils.createvideothumbnail(mvideofilename ,mediastore.images.thumbnails.mini_kind) } @override public void onerror(cameradevice camera, int i) { } };
Comments
Post a Comment