Image is stretching while capturing video using mediarecorder - android-camera

I have made an application in which I am capturing video using MediaRecorder.But when preview starts on device it seems that image is stretching I just gone through all the related question here or on google but didn't get success.Here is my code.
video.xml
<SurfaceView
android:id="#+id/camera_view"
android:layout_width="fill_parent"
android:layout_height="250dp"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp" />
Video.java file configuration
public void startRecording() {
try {
if(some codition){
// recording call.
setCameraDisplayOrientaion();
camera.unlock();
mediaRecorder.setCamera(camera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder
.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
mediaRecorder.setAudioEncodingBitRate(16);
mediaRecorder.setAudioSamplingRate(44100);
CamcorderProfile profile = CamcorderProfile.QUALITY_1080P == CamcorderProfile.QUALITY_HIGH
|| CamcorderProfile
.hasProfile(CamcorderProfile.QUALITY_480P) ? CamcorderProfile
.get(cameraId, CamcorderProfile.QUALITY_480P)
: CamcorderProfile.get(cameraId,
CamcorderProfile.QUALITY_HIGH);
profile.videoFrameRate = 15;
profile.videoBitRate = 150000;
profile.audioBitRate = 12200;
mediaRecorder.setProfile(profile);
mediaRecorder.setOutputFile(string);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (Exception e) {
Log.e(ResponseActivity.class.toString(), e.getMessage());
releaseMediaRecorder();
}
} else {
mediaRecorder = new MediaRecorder();
setCameraDisplayOrientaion();
camera.unlock();
mediaRecorder.setCamera(camera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
mediaRecorder.setAudioEncodingBitRate(16);
mediaRecorder.setAudioSamplingRate(44100);
CamcorderProfile profile = CamcorderProfile.QUALITY_1080P == CamcorderProfile.QUALITY_HIGH
|| CamcorderProfile
.hasProfile(CamcorderProfile.QUALITY_480P) ? CamcorderProfile
.get(cameraId, CamcorderProfile.QUALITY_480P)
: CamcorderProfile.get(cameraId,
CamcorderProfile.QUALITY_HIGH);
profile.videoFrameRate = videoFrameRate;
profile.videoBitRate = videoBitrate;
profile.audioBitRate = audioBitrate;
mediaRecorder.setProfile(profile);
mediaRecorder.setOutputFile(fullQuestionPath);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (Exception e) {
Log.e(ResponseActivity.class.toString(), e.getMessage());
releaseMediaRecorder();
}
}
} catch (Exception e) {
}
}
Please let me know that what configuration need to change here,Any help would be appreciable.

Related

Camera2: onCaptureCompleted() is not called

I recently started learning camera2 api, but I have some trouble.
This code can be run when camera is emulated.
However, when I use Webcam0 or virtual scene it will stuck after executing captureburst(), and without error message.
It only shows that "The application may be doing too much work on its main thread."
I check that it will call onCaptureStarted(), but will not call onCaptureCompleted().
AVD Manager: API30 Pixel 3
public void takePicture(){
if(cameraDevice == null){
return ;
}
try {
picturesRequestBuilder = cameraDevice.createCaptureRequest(cameraDevice.TEMPLATE_STILL_CAPTURE);
//
mImageReader.setOnImageAvailableListener(new OnImageAvailableListener(),mainHandler);
//imageSurface = mImageReader.getSurface();
//
picturesRequestBuilder.addTarget(imageSurface);
picturesRequestBuilder.addTarget(surface);
picturesRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
//
CaptureRequest captureRequest = picturesRequestBuilder.build();
ArrayList<CaptureRequest> captureRequests = new ArrayList<>();
for(int i=0;i<5;i++){
captureRequests.add(captureRequest);
}
mCameraCaptureSession.captureBurst(captureRequests, new CaptureCallback(),mainHandler);
}
catch (CameraAccessException e) {
e.printStackTrace();
}
Log.d("test","finished");
}
///////////////
private void setupCamera(){
cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
try{
cameraIdList = cameraManager.getCameraIdList();
cameraId = cameraManager.getCameraIdList()[0]; // 取得後置鏡頭
cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);
} catch (CameraAccessException e){
e.printStackTrace();
}
StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
Size[] outputSizes = streamConfigurationMap.getOutputSizes(ImageFormat.JPEG);
/////camera支援最大的高與寬////
cameraWidth = outputSizes[0].getWidth();
cameraHeight = outputSizes[0].getHeight();
//////////////////////////////
REQUIRED_PERMISSIONS.add(android.Manifest.permission.CAMERA);
REQUIRED_PERMISSIONS.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
/////////
public void setPreview(){
List<Surface> outputSurface = new ArrayList<>(2);
SurfaceTexture surfaceTexture = cameraPreview.getSurfaceTexture();
ImageReader imageReader = ImageReader.newInstance( 1920 , 1080, ImageFormat.JPEG, 1);
imageReader.setOnImageAvailableListener(new OnImageAvailableListener(), childHandler);
mImageReader = imageReader;
imageSurface = imageReader.getSurface();
surface = new Surface(surfaceTexture);
outputSurface.add(surface);
outputSurface.add(imageSurface);
try{
previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
previewRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(outputSurface, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
if(cameraDevice == null){
return;
}
mCameraCaptureSession = cameraCaptureSession;
try {
previewRequestBuilder.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO);
mCameraCaptureSession.setRepeatingRequest(previewRequestBuilder.build(), null, childHandler);
}catch (CameraAccessException e) {
Log.d("TAG", "Error creating the preview session");
Log.d("TAG", e.getMessage());
}
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Log.d("fail","Failed");
}
}, childHandler);
} catch (CameraAccessException e) {
Log.d("TAG", "Error setting up the camera preview");
Log.d("TAG", e.getMessage());
}
}
If you're using the emulator virtual scene for Android 11 beta (API level 30), there's a known bug in JPEG capture, which you may be running into: https://buganizer.corp.google.com/issues/160382725
If it's the bug in question, the entire system logcat should show a crash involving a JPEG library for the camera HAL process.
This will be fixed in a later update to the Android 11 SDK.

Caused by: org.eclipse.swt.SWTException: Invalid thread access

I get "Invalid thread access" in below code. I am not sure where I have written wrong code. My main intention to write the code is to just display subtask (what is happening behind the scene) so I have added subtask before method called.
#Override
public void handleEvent(Event event)
{
if((event.keyCode == SWT.CR || event.keyCode == 13 || event.type == SWT.Selection) && btnAdd.isEnabled())
{
final PreferencesMO permo = new PreferencesMO();
permo.updatePreferences();
permo.updateDocumentNumber();
final ProjectMO pmo = new ProjectMO();
final CoverSheetMO csmo = new CoverSheetMO();
final CommonError cmerror = new CommonError();
final ParameterConfigurationMO pamo = new ParameterConfigurationMO();
final SnippetNew s = new SnippetNew();
final String projName = txtpname.getText();
Display.getDefault().asyncExec(new Runnable()
{
public void run()
{
try
{
new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() {
#Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException
{
monitor.beginTask("Import Data", IProgressMonitor.UNKNOWN);
monitor.subTask("Connecting to databse...");
for(int i=0;i<=100;i++)
{
s.method1(i);
}
//monitor.worked(1);
try { Thread.sleep(2000); } catch (Exception e) { }
monitor.subTask("Analysing Data...");
try { Thread.sleep(2000); } catch (Exception e) { }
if(!projName.equals(""))
{
monitor.subTask("Updating coversheet ...");
try { Thread.sleep(2000); } catch (Exception e) { }
cmerror.updateCoverSheetStatusforNewProject();
monitor.subTask("Inserting Project ...");
try { Thread.sleep(2000); } catch (Exception e) { }
pmo.addProjectManager(projName,"T");
monitor.subTask("Searching Project ID ...");
try { Thread.sleep(2000); } catch (Exception e) { }
String p_id = pmo.searchprojectID(projName);
permo.insertDocumentNumber(p_id);
monitor.subTask("Inserting data into coversheet ...");
try { Thread.sleep(2000); } catch (Exception e) { }
csmo.insertCoversheet(p_id);
pamo.insertParameterConfiguration(p_id);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setText("Demo Tool - "+projName);
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
AuditLogs view = (AuditLogs) page.findView(AuditLogs.ID);
IEditorPart editorPart = page.getActiveEditor();
StackedLambdaChartInput input = new StackedLambdaChartInput();
AnalysisResult_MetricsChartInput metricsinput = new AnalysisResult_MetricsChartInput();
StackedLambdaChart_HorizantalInput stackedhorizantalinput = new StackedLambdaChart_HorizantalInput();
AnalysisResult_Metrics_HorizantalChartInput metricshorizantalinput = new AnalysisResult_Metrics_HorizantalChartInput();
BarChartInput inpuit = new BarChartInput();
BarChart_HorizantalInput barchart_horizantalinput = new BarChart_HorizantalInput();
AuditLogMO auditlog = new AuditLogMO();
monitor.subTask("Fetching audit logs to display ...");
try { Thread.sleep(2000); } catch (Exception e) { }
java.util.List<java.util.List<String>> auditlogs = auditlog.searchAuditLog(null,null);
view.table(auditlogs);
try
{
handlerService.executeCommand(AuditLogView.ID, new Event());
handlerService.executeCommand(ErrorLogView.ID, new Event());
handlerService.executeCommand(DesignHierarchyHandler.ID, new Event());
if(myeditor != null)
{
if(myeditor instanceof CoverSheet)
{
handlerService.executeCommand(CoverSheetHandler.ID, new Event());
}
else if(myeditor instanceof ParameterConfigurations)
{
handlerService.executeCommand(ParameterConfigurationHandler.ID, new Event());
}
}
}
catch (ExecutionException | NotDefinedException | NotEnabledException | PartInitException| NotHandledException e1)
{
e1.printStackTrace();
}
Constant con = new Constant();
con.createNewProject();
}
//shell.close();
monitor.done();
}
});
}
catch (InvocationTargetException | InterruptedException e)
{
e.printStackTrace();
}
}
});
}
}
Put your progress monitor as below :
Display.getDefault().asyncExec( new Runnable()
{
IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() {
#Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException
{
monitor.beginTask("Import Data", IProgressMonitor.UNKNOWN);
monitor.subTask("Connecting to databse...");
for(int i=0;i<=100;i++)
}
If you want the workbench page, that also has to be called inside a UI thread like above.
You can't access UI code in the background thread used for the IRunnableWithProgress code.
So you must get the values of controls in the UI thread before you run the progress dialog.
You also can't access things like IWorkbenchPage in the background thread. If you want to update UI objects from a non-UI thread, you need to use Display.asyncExec or Display.syncExec to run the updating code in the UI thread.

Camera Zoom in/out null pointer exception

My code works fine when i add the zoom code it gives null pointer exception.
I have written the below code inside the preview class. I am new in android please help thanks in advance.
my code is
int currentZoomLevel = 0, maxZoomLevel = 0;
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
parameters = mCamera.getParameters();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Display display = ((WindowManager) context
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (display.getRotation() == Surface.ROTATION_0) {
try {
parameters.setPreviewSize(height, width);
mCamera.setDisplayOrientation(90);
} catch (Exception e) {
e.printStackTrace();
}
}
if (display.getRotation() == Surface.ROTATION_90) {
try {
parameters.setPreviewSize(width, height);
} catch (Exception e) {
e.printStackTrace();
}
}
if (display.getRotation() == Surface.ROTATION_180) {
try {
parameters.setPreviewSize(height, width);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (display.getRotation() == Surface.ROTATION_270) {
try {
parameters.setPreviewSize(width, height);
mCamera.setDisplayOrientation(180);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is whera i start zooming. i have add zoom control in side my layout
ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoom);
if (parameters.isZoomSupported()) {
final int maxZoomLevel = parameters.getMaxZoom();
Log.i("max ZOOM ", "is " + maxZoomLevel);
zoomControls.setIsZoomInEnabled(true);
zoomControls.setIsZoomOutEnabled(true);
zoomControls.setOnZoomInClickListener(new OnClickListener() {
public void onClick(View v) {
if (currentZoomLevel < maxZoomLevel) {
currentZoomLevel++;
mCamera.startSmoothZoom(currentZoomLevel);
parameters.setZoom(currentZoomLevel);
mCamera.setParameters(parameters);
}
}
});
zoomControls.setOnZoomOutClickListener(new OnClickListener() {
public void onClick(View v) {
if (currentZoomLevel > 0) {
currentZoomLevel--;
parameters.setZoom(currentZoomLevel);
mCamera.setParameters(parameters);
}
}
});
} else
zoomControls.setVisibility(View.GONE);
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}

How to show Custom Message in Place of Null Date of Birth

I am writing an app in which i am fetching List of Facebook friends with their profile picture, name and dob
but some of my friends have not given their Birthday Dates, so in place of Birthday i am getting null by default, but now in place of null i want to show: Birthday Not Mentioned.
see below screen shot of my existing app:
Like: Vikas Rana has given DOB on facebook and AJay November has not given DOB on Facebook
> VikY
January 1
> AJamber
Null
Here, in place Null i want to show : Birthday Not Mentioned
FriendsList.java:
public View getView(int position, View convertView, ViewGroup parent) {
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e) {
}
FriendItem friendItem;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listfb_friends, null);
friendItem = new FriendItem();
convertView.setTag(friendItem);
} else {
friendItem = (FriendItem) convertView.getTag();
}
friendItem.friendPicture = (ImageView) convertView
.findViewById(R.id.picture);
friendItem.friendName = (TextView) convertView
.findViewById(R.id.name);
friendItem.friendDob = (TextView) convertView
.findViewById(R.id.dob);
friendItem.friendLayout = (RelativeLayout) convertView
.findViewById(R.id.friend_item);
try {
String uid = jsonObject.getString("uid");
String url = jsonObject.getString("pic_square");
friendItem.friendPicture.setImageBitmap(picturesGatherer
.getPicture(uid, url));
} catch (JSONException e) {
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
try {
friendItem.friendName.setText(jsonObject.getString("name"));
if(!friendItem.friendDob.equals(""))
{
friendItem.friendDob.setText(jsonObject.getString("birthday"));
}
else
{
friendItem.friendDob.setText("Birthday Not Mentioned");
}
} catch (JSONException e) {
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
listofshit.put(position, friendItem);
return convertView;
}
and if i am writing code something like this:
try {
friendItem.friendName.setText(jsonObject.getString("name"));
friendItem.friendDob.setText(jsonObject.getString("birthday"));
} catch (JSONException e) {
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
finally
{
friendItem.friendDob.setText("Birthday Not Mentioned");
}
so i am getting Birthday Not Mentioned for all facebook friends Birthdays, even for them also those have mentioned.
try this one.
try{
if(jsonObject.getString("birthday")!= null && !jsonObject.getString("birthday").equals("")){
friendItem.friendDob.setText(jsonObject.getString("birthday"));
}else{
friendItem.friendDob.setText("Birthday Not Mentioned");
}
}catch(JSONException e){
e.printStackTrace();
}
Where you are getting NullPointerException use try-catch over it.
You might have done it I think. Now just set the text "Birthday Not Mentioned" over the textview/edittext (whatever you are using to show d.o.b) by writing code in catch block.
Just use:-
try {
friendItem.friendName.setText(jsonObject.getString("name"));
friendItem.friendDob.setText(jsonObject.getString("birthday"));
}
catch (Exception e) {
friendItem.friendName.setText("Name"); // try it for now.
friendItem.friendDob.setText("Birthday Not Mentioned"); // Have to be here.
}
Just try with this code:
try
{
friendItem.friendName.setText(jsonObject.getString("name"));
friendItem.friendDob.setText(jsonObject.getString("birthday"));
if(!(jsonObject.getString("birthday").equalsIgnoreCase("null")))
{
friendItem.friendDob.setText(jsonObject.getString("birthday"));
}
else
{
friendItem.friendDob.setText("Birthday Not Mentioned");
}
} catch (JSONException e)
{
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
listofshit.put(position, friendItem);
return convertView;
}

How can i attach multiple images with email in Blackberry?

I want to attach multiple images with email in BB. How can I do this? Does any body have an idea? please help me.Below is my code which works fine when i send only one image with email. so what modification should I make in my code for attaching multiple images.
public static void SendMailAttachment(Bitmap screenshot)
{
String htmlContent = "String" ;
try
{
Multipart mp = new Multipart();
Message msg = new Message();
Address[] addresses = {new Address("","")};
for (int i = 0; i<2 ; i++)
{
PNGEncodedImage img = PNGEncodedImage.encode(screenshot);
SupportedAttachmentPart pt = new SupportedAttachmentPart(mp, img.getMIMEType(),
"Weed.png", img.getData());
mp.addBodyPart(pt);
}
msg.setContent(mp);
msg.setContent(htmlContent);
msg.addRecipients(RecipientType.TO, addresses);
msg.setSubject("Subject");
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(msg));
}
catch (AddressException ex)
{
System.out.println("Exception -->"+ex.getMessage());
}
catch (MessagingException ex)
{
System.out.println("Exception -->"+ex.getMessage());
}
}
Thanx in advance.
following code can be used to attach multiple images or files.
public void upload()
{
Multipart mp = new Multipart();
String fileName = null;
for (int i = 0; i<2 ; i++)
{
// Dialog.alert(image.);
byte[] stream = readStream("file:///SDCard/IMG00001-20110404-1119.JPEG");
SupportedAttachmentPart sap = new SupportedAttachmentPart(mp, MIMETypeAssociations.getMIMEType("IMG00001-20110404-1119.JPEG"),"IMG00001-20110404-1119.JPEG", stream);
mp.addBodyPart(sap);
}
TextBodyPart tbp = new TextBodyPart(mp,"test bodyString");
mp.addBodyPart(tbp);
Folder folders[] = Session.getDefaultInstance().getStore().list(Folder.SENT);
Message message = new Message(folders[0]);
Address[] toAdds = new Address[1];
try {
toAdds[0] = new Address("testmailid", null);
message.addRecipients(Message.RecipientType.TO,toAdds);
// message.setFrom(new InternetAddress(_from));
// message.addRecipients(Message.RecipientType.FROM,toAdds);
message.setContent(mp);
message.setSubject("test subject");
Transport.send(message);
Dialog.alert("message send successfully.");
} catch (AddressException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
Dialog.alert(e.getMessage());
} catch (MessagingException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
private byte[] readStream(String path)
{
InputStream in = null;
FileConnection fc = null;
byte[] bytes = null;
try
{
fc = (FileConnection) Connector.open(path);
if (fc !=null && fc.exists())
{
in = fc.openInputStream();
if (in !=null)
{
bytes = IOUtilities.streamToBytes(in);
}
}
}
catch(IOException e)
{
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch(IOException e)
{
}
try
{
if (fc !=null)
{
fc.close();
}
}
catch(IOException e)
{
}
}
return bytes;
}
i have used this code. it works fine.
Just create a new SupportedAttachmentPart for each image and add them to the message with the addBodyPart method.
Once the multipart is populated with the body part and the attachment parts, call msg.setContent(mp).