我在相机应用程序上工作,所以我已经在片段中实现了相机预览,因此结果它拉伸预览,在布局中我使用表面视图它在前置摄像头上工作正常,但它在后置摄像头中拉伸了预览是我的代码。
public class Camera_fragment extends Fragment implements SurfaceHolder.Callback, FragmentInterface {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
private Camera.Size mPreviewSize;
int CameraId;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_games, container, false);
//getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
display = ((WindowManager) getActivity().getSystemService(getActivity().WINDOW_SERVICE)).getDefaultDisplay();
sharedpreferences = getActivity().getSharedPreferences("turnstrr", getActivity().MODE_PRIVATE);
getActivity().getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) rootView.findViewById(R.id.camera_preview);
Imgvw1 = (ImageView) rootView.findViewById(R.id.imageView21);
imgvw2 = (ImageView) rootView.findViewById(R.id.imageView17);
imgvw3 = (ImageView) rootView.findViewById(R.id.imageView19);
imgvw4 = (ImageView) rootView.findViewById(R.id.imageView20);
Img_switch_camera = (ImageView) rootView.findViewById(R.id.Switch_camera);
img_cross1 = (ImageView) rootView.findViewById(R.id.imageView22);
imgcross2 = (ImageView) rootView.findViewById(R.id.imageView23);
img_cross3 = (ImageView) rootView.findViewById(R.id.imageView24);
imgcross4 = (ImageView) rootView.findViewById(R.id.imageView25);
Img_camera_click = (ImageView) rootView.findViewById(R.id.camera_click);
Btn_next = (Button) rootView.findViewById(R.id.btn_Next);
mProgressBar = (ProgressBar) rootView.findViewById(R.id.pb_loading);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
tb = new TinyDB(getActivity());
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// recorder = new MediaRecorder();
// initRecorder();
Img_switch_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
camera.stopPreview();
} catch (java.lang.RuntimeException e) {
e.printStackTrace();
}
camera.release();
if (CameraId == Camera.CameraInfo.CAMERA_FACING_BACK) {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
CameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
} else {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
CameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
Camera.Size optimalSize = getOptimalPreviewSize(sizes, getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
// You need to choose the most appropriate previewSize for your app
// Camera.Size optimalSize = parameters.getSupportedPreviewSizes().get(0);
// previewSize.width = 720;
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
// start preview with new settings
camera.setParameters(parameters);
// Set the holder size based on the aspect ratio
// int size = Math.min(display.getWidth(), display.getHeight());
// double ratio = (double) previewSize.width / previewSize.height;
//
// surfaceHolder.setFixedSize((int) (size * ratio), size);
try {
camera.setPreviewDisplay(surfaceHolder);
} catch (IOException e) {
e.printStackTrace();
}
camera.setDisplayOrientation(90);
camera.startPreview();
}
});
@Override
public void surfaceCreated(SurfaceHolder holder) {
//camera = Camera.open();
try {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
Camera.Size optimalSize = getOptimalPreviewSize(sizes, getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
// Camera.Size optimalSize = null;
// optimalSize.width= 1280;
// optimalSize.height= 720;
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
// You need to choose the most appropriate previewSize for your app
// Camera.Size previewSize = parameters.getSupportedPreviewSizes().get(0);
// // previewSize.width = 720;
// parameters.setPreviewSize(previewSize.width, previewSize.height);
// start preview with new settings
camera.setParameters(parameters);
CameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
} catch (java.lang.RuntimeException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Fail to connect to camera service", Toast.LENGTH_LONG).show();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(0, info);
int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
//int currentapiVersion = android.os.Build.VERSION.SDK_INT;
// do something for phones running an SDK before lollipop
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
Camera.Size optimalSize = getOptimalPreviewSize(sizes, getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
// Camera.Size optimalSize = null;
// optimalSize.width= 1280;
// optimalSize.height= 720;
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
// You need to choose the most appropriate previewSize for your app
// Camera.Size previewSize = parameters.getSupportedPreviewSizes().get(0);
// // previewSize.width = 720;
// parameters.setPreviewSize(previewSize.width, previewSize.height);
// start preview with new settings
camera.setParameters(parameters);
// Set the holder size based on the aspect ratio
// int size = Math.min(display.getWidth(), display.getHeight());
// double ratio = (double) optimalSize.width / optimalSize.height;
//
// surfaceHolder.setFixedSize((int) (size * ratio), size);
camera.setPreviewDisplay(surfaceHolder);
camera.setDisplayOrientation(result);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// camera.stopPreview();
// if (camera != null) {
// camera.release();
// camera = null;
// }
}
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.05;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Find size
for (Camera.Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
try {
fos.write(data);
} catch (NullPointerException e) {
e.printStackTrace();
}
fos.close();
camera.startPreview();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
// String s = null;
// try {
// FileReader fd = new FileReader();
//
// s = fd.getFileAsString(pictureFile);
// Array_items.add(s);
// }catch (OutOfMemoryError e){
// e.printStackTrace();
// }
String path = pictureFile.getAbsolutePath();
// if (Array_items.size() == 1) {
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// options.inSampleSize = 5;
// Bitmap bitmap = BitmapFactory.decodeFile(path, options);
// Imgvw1.setImageBitmap(bitmap);
// return;
// // Picasso.with(getActivity()).load(pictureFile).into(Imgvw1);
// } else if (Array_items.size() == 2) {
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// options.inSampleSize = 5;
// Bitmap bitmap = BitmapFactory.decodeFile(path, options);
// imgvw2.setImageBitmap(bitmap);
// // Picasso.with(getActivity()).load(pictureFile).into(imgvw2);
// } else if (Array_items.size() == 3) {
// try {
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// options.inSampleSize = 5;
// Bitmap bitmap = BitmapFactory.decodeFile(path, options);
// imgvw3.setImageBitmap(bitmap);
// } catch (OutOfMemoryError e) {
// e.printStackTrace();
// }
//
// // Picasso.with(getActivity()).load(pictureFile).into(imgvw3);
// } else if (Array_items.size() == 4) {
// try {
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// options.inSampleSize = 5;
// Bitmap bitmap = BitmapFactory.decodeFile(path, options);
// imgvw4.setImageBitmap(bitmap);
// } catch (OutOfMemoryError e) {
// e.printStackTrace();
// }
// // Picasso.with(getActivity()).load(pictureFile).into(imgvw4);
// }
// ImageView img_cross1, imgcross2, img_cross3, imgcross4;
if (Array_items.size() < 4) {
Array_items.add(path);
Img_camera_click.setImageResource(R.drawable.camera_blue_normal);
tb.putListString("list", Array_items);
if (Strfor_img1.contentEquals("niomage1")) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 5;
try {
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
ExifInterface exif = null;
try {
exif = new ExifInterface(path);
} catch (IOException e) {
e.printStackTrace();
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap bmRotated = rotateBitmap(bitmap, orientation);
Imgvw1.setImageBitmap(bmRotated);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
Strfor_img1 = "setimage1";
img_cross1.setVisibility(View.VISIBLE);
return;
// Picasso.with(getActivity()).load(pictureFile).into(Imgvw1);
} else if (Strfor_img2.contentEquals("noimag2")) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 5;
try {
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
imgvw2.setImageBitmap(bitmap);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
Strfor_img2 = "setimage2";
imgcross2.setVisibility(View.VISIBLE);
return;
// Picasso.with(getActivity()).load(pictureFile).into(imgvw2);
} else if (Strfor_img3.contentEquals("noimage3")) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 5;
try {
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
imgvw3.setImageBitmap(bitmap);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
Strfor_img3 = "setimage3";
img_cross3.setVisibility(View.VISIBLE);
return;
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
// Picasso.with(getActivity()).load(pictureFile).into(imgvw3);
} else if (Strfor_img4.contentEquals("noimage4")) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 5;
try {
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
imgvw4.setImageBitmap(bitmap);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
Strfor_img4 = "setimage4";
imgcross4.setVisibility(View.VISIBLE);
return;
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
// Picasso.with(getActivity()).load(pictureFile).into(imgvw4);
}
} else {
Toast.makeText(getActivity(), "your post is ready for upload", Toast.LENGTH_LONG).show();
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Turnstr");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("Turnstr", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
private static File getOutputMedia_video_File() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Turnstr");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("Turnstr", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "video" + timeStamp + ".mp4");
return mediaFile;
}
public class FileReader {
public String getFileAsString(File file) {
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
StringBuffer sb = new StringBuffer();
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
sb.append(dis.readLine() + "\n");
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
@Override
public void onPause() {
super.onPause();
if (camera != null) {
// java.lang.RuntimeException
try {
camera.stopPreview();
camera.release();
} catch (java.lang.RuntimeException e) {
e.printStackTrace();
}
}
}
private void releaseCamera() {
if (camera != null) {
camera.release(); // release the camera for other applications
camera = null;
}
}
private boolean prepareMediaRecorder() {
// camera = getCameraInstance();
recorder = new MediaRecorder();
camera.unlock();
recorder.setCamera(camera);
// recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_LOW));
Video_path = getOutputMedia_video_File().getAbsolutePath();
recorder.setOutputFile(Video_path);
//Array_items.add(Video_path);
recorder.setMaxDuration(60000); // Set max duration 60 sec.
recorder.setMaxFileSize(5000000); // Set max file size 5M
recorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
try {
recorder.prepare();
//recorder.start();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;
}
private void releaseMediaRecorder() {
if (recorder != null) {
recorder.reset(); // clear recorder configuration
recorder.release(); // release the recorder object
recorder = null;
camera.lock(); // lock camera for later use
}
}
private Camera getCameraInstance() {
// TODO Auto-generated method stub
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
public static Bitmap getVidioThumbnail(String path) {
Bitmap bitmap = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
bitmap = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.MICRO_KIND);
if (bitmap != null) {
return bitmap;
}
}
// MediaMetadataRetriever is available on API Level 8 but is hidden until API Level 10
Class<?> clazz = null;
Object instance = null;
try {
clazz = Class.forName("android.media.MediaMetadataRetriever");
instance = clazz.newInstance();
final Method method = clazz.getMethod("setDataSource", String.class);
method.invoke(instance, path);
// The method name changes between API Level 9 and 10.
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD) {
bitmap = (Bitmap) clazz.getMethod("captureFrame").invoke(instance);
} else {
final byte[] data = (byte[]) clazz.getMethod("getEmbeddedPicture").invoke(instance);
if (data != null) {
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
if (bitmap == null) {
bitmap = (Bitmap) clazz.getMethod("getFrameAtTime").invoke(instance);
}
}
} catch (Exception e) {
bitmap = null;
} finally {
try {
if (instance != null) {
clazz.getMethod("release").invoke(instance);
}
} catch (final Exception ignored) {
}
}
return bitmap;
}
public static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
matrix.setRotate(90);
break;
// return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
// try {
bitmap.recycle();
// }catch (java.lang.RuntimeException e){
// e.printStackTrace();
// }
return bmRotated;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
}
}