2015-10-30 2 views
0

Я работаю над приложением, которое использует предварительный просмотр камеры для съемки и отображения их в виде сетки в другой деятельности. Но когда я беру картинку с картинками, она сохраняется на моей карте галактики S4 SD в ландшафте, а также отображает ее в виде сетки в ландшафте!сохранение фотографий в ориентации на потоки

Image 1

Image 2

Gridview Avtivity:

public class GridViewActivity extends Activity { 

private ImageAdapter imageAdapter; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.grid_view); 

    GridView gridview = (GridView) findViewById(R.id.gridview); 
    imageAdapter = new ImageAdapter(this); 
    gridview.setAdapter(imageAdapter); 

    String ExternalStorageDirectoryPath = Environment 
      .getExternalStorageDirectory() 
      .getAbsolutePath(); 

    String targetPath = ExternalStorageDirectoryPath + "/JCG Camera"; 

    File targetDirector = new File(targetPath); 

    File[] files = targetDirector.listFiles(); 
    for (File file : files){ 

     imageAdapter.add(file.getAbsolutePath()); 
    } 
} 

в ImageAdapter:

void add(String path){ 
    this.path = path; 
    imageList.add(path); 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView imageView; 
    if (convertView == null) { 
     imageView = new ImageView(context); 
     imageView.setLayoutParams(new GridView.LayoutParams(320, 320)); 
     imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
     imageView.setPadding(5, 5, 5, 5); 
    } else { 
     imageView = (ImageView) convertView; 
    } 

    Bitmap bm = decodeSampledBitmapFromUri(imageList.get(position), 320, 320); 
    imageView.setImageBitmap(bm); 
    return imageView; 
} 

public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) { 

    Bitmap bm = null; 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(path, options); 
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

    options.inJustDecodeBounds = false; 
    bm = BitmapFactory.decodeFile(path, options); 

    return bm; 
} 

public int calculateInSampleSize(

    BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 
     if (width > height) { 
      inSampleSize = Math.round((float)height/(float)reqHeight);  
     } else { 
      inSampleSize = Math.round((float)width/(float)reqWidth);  
     } 
    } 

    return inSampleSize;  
} 

активности камеры:

private PictureCallback getPictureCallback() { 
    PictureCallback picture = new PictureCallback() { 

     @Override 
     public void onPictureTaken(byte[] data, Camera camera) { 

      //make a new picture file 

      File pictureFile = getOutputMediaFile(); 

      if (pictureFile == null) { 
       return; 
      } 
      try { 

       //write the file 

       FileOutputStream fos = new FileOutputStream(pictureFile); 
       fos.write(data); 
       fos.close(); 
       Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG); 
       toast.show(); 

      } catch (FileNotFoundException e) { 
      } catch (IOException e) { 
      } 

      //refresh camera to continue preview 

      mPreview.refreshCamera(mCamera); 
     } 
    }; 
    return picture; 
} 

private static File getOutputMediaFile() { 

    //make a new file directory inside the "sdcard" folder 

    File mediaStorageDir = new File("/sdcard/", "JCG Camera"); 

    //if this "JCGCamera folder does not exist 

    if (!mediaStorageDir.exists()) { 

     //if you cannot make this folder return 

     if (!mediaStorageDir.mkdirs()) { 
      return null; 
     } 
    } 


    //take the current timeStamp 

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
    File mediaFile; 

    //and make a media file: 

    mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); 
    return mediaFile; 
} 

Я читал о EXIF ​​и exifinerface, но я не знаю, как использовать его в своем коде!

+0

Возможный дубликат [Как повернуть и перевернуть растровое изображение в onPictureTaken] (http://stackoverflow.com/questions/16228654/how-to-rotate-and-flip-bitmap-in-onpicturetaken) –

ответ

0

ExiftInterface - хороший подход, я думаю. Им остается только, что у вас должен быть механизм, который подскажет, каким образом ваше изображение должно быть повернуто (например, по часовой стрелке, против часовой стрелки). Это то, что я использую для поворота изображения.

try { 
    //You must replace _filePaths.get(position) with the desired object 
    //You are trying to extract the rotation info. In your case is your data 
    //But I think you have to save your image first, before you can rotate it. 
    ExifInterface exif = new ExifInterface(_filePaths.get(position)); 

    //Here you extract the image's rotation info. 
    int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); 

    //Here you can convert it to degrees. Using helper method. 
    int roationInDegrees = exifToDegress(rotation); 
    Matrix matrix = new Matrix(); 

    //This is where you check if the rotation of the image is not what you want. 0f indicates a portait Image. 
    if(rotation != 0f){ 

    //Here you specify which way you want to rotate your bitmap according 
    //To the result of helper method. 
    matrix.preRotate(roationInDegrees); 
    image = Bitmap.createBitmap(image,0, 0, imageWidth, imageWidth, matrix, true); 
} 
} catch (IOException e1) { 
    e1.printStackTrace(); 
    Log.d("activity#fail", e1.getMessage()); 
} 

private int exifToDegress(int exifOrientation) { 
    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; } 
    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; } 
    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; }    
    return 0; 
} 

Убедитесь, что вы положили код внутри Попробуйте и поймать в случае изображения ваши пытаются повернуть не содержит «Ориентацию» информации. Попробуйте добавить этот код прямо перед записью «данных» с помощью объекта fileoutputstream.

Удачи.

Смежные вопросы