I am implementing a custom camera in android. One of the phones that I am using the default display orientation is landscape mode. The preview of the image looks good when taking the picture. Nonetheless, when the immage is rotated and saved the image becomes distorted.
This is the code I am using to rotate the image:
Code:
Display display = ((WindowManager) MyCamera.this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
if (rotation == Surface.ROTATION_0) {
rotation = 90;
} else if (rotation == Surface.ROTATION_90) {
rotation = 180;
} else if (rotation == Surface.ROTATION_180) {
rotation = 270;
} else if (rotation == Surface.ROTATION_270) {
rotation = 360;
}
DisplayMetrics metrics = getResources().getDisplayMetrics();
Options options = new BitmapFactory.Options();
options.inDither = false;
options.inScaled = false;
options.inDensity=metrics.densityDpi;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bm = BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length, options);
Matrix m = new Matrix();
m.postRotate(rotation);
Bitmap nbm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
file = MyCamera.this.saveBitmap(nbm);
This is the code I'm using to save Bitmap image:
Code:
private File saveBitmap(Bitmap image) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
Log.d(TAG,"Error creating media file, check storage permissions: ");// e.getMessage());
return null;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
finish();
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
finish();
}
return pictureFile;
}
Here are some examples on how the image looks in camera preview mode and how it looks after it is saved on the phones external storage.
Related
I have this code below. The problem is i set the orientation of camera to portrait, even preview is portrait. But when i playback that video i see it in landscape mode. Do you guys know why and how i can fix this? Is there a way to rotate VideoView when i playback or to rotate video itself after recording..? I beg you, help me, anywhere i ask nobody knows why and how to fix it...
Here is the code:
Code:
public class BetaRecordActivity extends Activity {
private Preview preview;
private Camera camera;
private MediaRecorder recorder;
private int defaultCameraId;
private int videoCount;
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.beta_record, menu);
return true;
}
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beta_record);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
initCameraAndPreview();
videoCount = 0;
preview.setOnTouchListener(new View.OnTouchListener() {
[user=439709]@override[/user]
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
releaseCamera();
getThatCamReady();
recorder.start();
videoCount ++;
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
stopRecording();
break;
}
return true;
}
});
}
[user=439709]@override[/user]
protected void onResume() {
super.onResume();
}
[user=439709]@override[/user]
protected void onPause() {
super.onPause();
}
private boolean getThatCamReady() {
camera = getCameraInstance();
setCameraDisplayOrientation(this, defaultCameraId, camera);
camera.unlock();
recorder = new MediaRecorder();
recorder.setCamera(camera);
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
File tempFile = new File(Environment.getExternalStorageDirectory(), "/rec/temp/video_" + String.valueOf(videoCount) + ".mp4");
recorder.setOutputFile(tempFile.getPath());
recorder.setMaxDuration(12500);
recorder.setMaxFileSize(7000000);
recorder.setPreviewDisplay(preview.getHolder().getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;
}
private void stopRecording() {
//timer.pause();
try {
recorder.stop();
} catch(RuntimeException stopException) {
// Handle the cleanup here
//badList.add(videoCount);
//videoCount--;
//RecordActivity.this.timeLeft.setText(String.valueOf(videoCount));
}
releaseMediaRecorder();
}
private void initCameraAndPreview() {
// Find the total number of cameras available
int numberOfCameras = Camera.getNumberOfCameras();
// Find the ID of the default camera
CameraInfo cameraInfo = new CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
defaultCameraId = i;
}
}
camera = getCameraInstance();
setCameraDisplayOrientation(this, defaultCameraId, camera);
preview = new Preview(this, camera);
FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
myCameraPreview.addView(preview);
}
private void releaseMediaRecorder(){
if (recorder != null) {
recorder.reset();
recorder.release();
recorder = null;
camera.lock();
}
}
private void releaseCamera(){
if (camera != null){
camera.release();
camera = null;
}
}
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 void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.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;
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.setDisplayOrientation(result);
}
}
Hi Droid-expert
For stock bootanimation in JB, there is a single threaded animation process/class inside. If I'd like to implement the power-on sound/tune as well. What's the best programming scheme/model it could be?
So far, by my understanding, I did something in BootAnimation.cpp in the following:
Did I do wrong? The handset boots up, it shows the animation first, and then the sound is played.
However, in a normal AOS adb shell session, try to run bootanimation, and it works fine (I mean both animation and sound are played at the same time)
Does the init is multi-threaded?
Anthony
class PlayerListener: public MediaPlayerListener, public Thread
{
public:
PlayerListener(): Thread(false), mp(NULL) {}
~PlayerListener() { delete mp; mp = NULL; }
virtual void notify(int, int, int, const Parcel *) {}
virtual bool threadLoop();
virtual status_t readyToRun();
private:
MediaPlayer* mp;
};
// ----------------------------------------------------------------------
bool PlayerListener::threadLoop()
{
if (mp != NULL)
mp->start();
sleep(100);
requestExit();
return false;
}
status_t PlayerListener::readyToRun()
{
int index = 7;
audio_devices_t device;
bool r;
mp = new MediaPlayer();
mp->setListener(this);
if (mp->setDataSource(SYSTEM_BOOTANIMATION_SOUND_FILE, NULL) == NO_ERROR) {
mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
mp->prepare();
mp->setLooping(false);
}
// AudioSystem::getStreamVolumeIndex(AUDIO_STREAM_ENFORCED_AUDIBLE, &index);
device = AudioSystem::getDevicesForStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
r = AudioSystem::setStreamVolumeIndex(AUDIO_STREAM_ENFORCED_AUDIBLE, index, device);
r = AudioSystem::getStreamVolumeIndex(AUDIO_STREAM_ENFORCED_AUDIBLE, &index, device);
if (index != 0) {
mp->seekTo(0);
// mp->start();
}
return NO_ERROR;
}
bool BootAnimation::threadLoop()
{
bool r;
sp<PlayerListener> player = new PlayerListener();
player->run("BootAnimatedMelody", PRIORITY_AUDIO);
if (mAndroidAnimation) {
r = android();
} else {
r = movie();
}
Hi,
I am developing an android app in which i am using csv file and displaying column contents as listview its displaying as [a,b,c,d] in single row how to display them in individual row in listview.Please any one help me how to achive this.
This is my csv file reading code using hashcode.
Code:
public static Map<String,ArrayList<String>> parseCsv(InputStreamReader reader, String separator, boolean hasHeader) throws IOException {
Map<String,ArrayList<String> > values = new LinkedHashMap<String,ArrayList<String>>();
List<String> columnNames = new LinkedList<String>();
BufferedReader br = null;
br = new BufferedReader(reader);
String line;
int numLines = 0;
while ((line = br.readLine()) != null) {
//if (StringUtils.isNotBlank(line)) {
//if (!line.startsWith("#")) {
String[] tokens = line.split(separator);
if (tokens != null) {
for (int i = 0; i < tokens.length; ++i) {
if (numLines == 0) {
columnNames.add(hasHeader ? tokens[i] : ("row_"+i));
} else {
ArrayList<String> column = values.get(columnNames.get(i));
if (column == null) {
column = new ArrayList<String>();
}
column.add(tokens[i]);
values.put(columnNames.get(i), column);
}
}
}
++numLines;
}
// }//
// }//
return values;
listview code is:
Code:
oslist.add(values);
ListView list = (ListView) findViewById(R.id.studentnames);
String name="name";
// Add it listview
ListAdapter adapter = new SimpleAdapter(this,
oslist, R.layout.student_list, new String[] { name }, new int[] { R.id.name});
list.setAdapter(adapter);
So i found this perfect code to be able to select zip from sd, but the list looks so basic and I would like to add icons (like one common icon for all dirs), however it seems too hard to do on my own, here is the code:
Code:
private void loadFileList(File path) {
this.currentPath = path;
List<String> r = new ArrayList<String>();
if (path.exists()) {
if (path.getParentFile() != null) r.add(PARENT_DIR);
FilenameFilter filter = new FilenameFilter() {
@SuppressLint("DefaultLocale")
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
if (!sel.canRead()) return false;
if (selectDirectoryOption) return sel.isDirectory();
else {
boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
return endsWith || sel.isDirectory();
}
}
};
String[] fileList1 = path.list(filter);
for (String file : fileList1) {
r.add(file);
}
}
fileList = (String[]) r.toArray(new String[]{});
}
whit ANDROID previous kitkat I was able to store an image on sd-card without problem, now, instead, I've a lot of difficult.
I can't understand how use a new Access Store Framework of Android Lollipop and I don't know if it is useful to case of mine.
This code below is a part of my project and it's worked perfectly
Code:
private Bitmap getBitmap(String url, String image){
String root = Environment.getExternalStorageDirectory().toString();
root = "/mnt/extSdCard/";
Bitmap bitmap = null;
File f=fileCache.getFile(url);
//from SD cache
bitmap = decodeFile(f);
if(bitmap!=null)
return bitmap;
try{
bitmap = BitmapFactory.decodeFile(root + image);
if(bitmap!=null){
return bitmap;
}
}catch (Exception e) {
e.printStackTrace();
}
//from web
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
Foto foto = new Foto();
try {
try{
foto = new ObjectMapper().readValue(new URL("........."),
Foto.class);
if(foto!=null){
String[] values = image.split("/");
File dir = new File(root + values[0]);
if (!dir.exists()) {
dir.mkdir();
String fname = values[1];
File file = new File (dir, fname);
bitmap = BitmapFactory.decodeByteArray(foto.getFoto(), 0, foto.getFoto().length);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}else{
String fname = values[1];
File file = new File (dir, fname);
bitmap = BitmapFactory.decodeByteArray(foto.getFoto(), 0, foto.getFoto().length);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//bitmap = decodeFile(f);
return bitmap;
}else{
return bitmap;
}
}catch(Exception e){
e.printStackTrace();
return null;
}
} catch (Exception ex){
if (ex instanceof SQLiteConstraintException){
bitmap = BitmapFactory.decodeByteArray(foto.getFoto(), 0, foto.getFoto().length);
return bitmap;
}else{
ex.printStackTrace();
return null;
}
}
}else{
return bitmap;
}
}
If I use `Environment.getExternalStorageDirectory().getAbsolutePath();` I can't get path of sd-card.
Thanks