2014-01-14 7 views
1

Я использую API-интерфейс камеры, чтобы сделать снимок. Мне нужно открывать камеру разных размеров в соответствии с моим размером изображения. Я следую примеру проекта, который мы получаем в Android sdk/sample/adroid-18 под названием «ApiDemo», вещь, которую я изменил, не задана камерой на setcontentview. Я установил камеру на макет кадра. сначала мой предварительный просмотр камеры был накрахмален, поэтому я получил камеру OptimalPreviewSize и сделал ширину и высоту параметра FrameLayout как wrap -content. Теперь предварительный просмотр камеры меньше, чем ImageView (размер, который я хочу). Если я задаю размер параметра FrameLayout как match-parent, тогда камера View будет растянута. Как решить эту проблему.Центр Обрезать изображение В правильном размере, чтобы установить на ImageView

найти эту ссылку для получения дополнительной информации. Android camera preview look strange

UPDATE

Мой размер камеры предварительного просмотра отлично теперь я использую на макете метод идея была у меня есть больше раскладку тогда мой ImageView а теперь камера предварительного просмотра выглядит хорошо. Теперь проблема, с которой я сталкиваюсь, задает образ правильного размера для этого. Я должен посередине обрезать и масштабировать в том же размере, что и изображение ImageView.this. Я получаю метод TakePicture и сохраняется в sdcard.

Для этого я использую этот метод: -

public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) { 
    int sourceWidth = source.getWidth(); 
    int sourceHeight = source.getHeight(); 

    // Compute the scaling factors to fit the new height and width, respectively. 
    // To cover the final image, the final scaling will be the bigger 
    // of these two. 
    float xScale = (float) newWidth/sourceWidth; 
    float yScale = (float) newHeight/sourceHeight; 
    float scale = Math.max(xScale, yScale); 

    // Now get the size of the source bitmap when scaled 
    float scaledWidth = scale * sourceWidth; 
    float scaledHeight = scale * sourceHeight; 

    // Let's find out the upper left coordinates if the scaled bitmap 
    // should be centered in the new size give by the parameters 
    float left = (newWidth - scaledWidth)/2; 
    float top = (newHeight - scaledHeight)/2; 

     // The target rectangle for the new, scaled version of the source bitmap will now 
     // be 
     RectF targetRect = new RectF(left+50, top, left + scaledWidth, top + scaledHeight+50); 
//  RectF targetRect = new RectF(0, 0, newWidth, newHeight/2); 
     // Finally, we create a new bitmap of the specified size and draw our new, 
     // scaled bitmap onto it. 
     Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig()); 
     Canvas canvas = new Canvas(dest); 
     canvas.drawBitmap(source, null, targetRect, null); 

     return dest; 
} 

Но качество результата изображения не good.Height Углов резки от верхнего и нижнего, и результата качества изображения не good.Pixels растяжения.

Не говорите мне использовать scaleType = Center_crop. Я не могу использовать его в своем случае и не хочу показывать кадр обрезки для пользователя, этот процесс не должен отображаться в пользовательском интерфейсе.

UPDATE

Я использовал метод раздувом для обрезки изображения от центра и масштаба в соответствии с моим размером ImageView

Bitmap dstBmp = ThumbnailUtils.extractThumbnail(source, newWidth, newHeight); 

Но растровое я получил не смотрит же на предварительный просмотр камеры, показанный на FrameLayout. потому что просмотр камеры большой. Я думаю, что этот код обрезал большую площадь. Я попытался уменьшить ширину и изменить высоту, но не получить то же обрезанное изображение, в котором я хочу.

Еще одна идея, которую я получил после того, как изображение обрезает последний кадр изображения, установленный автоматически на FrameLayout. мы можем получить этот набор кадров из Frame Layout. Как это возможно?

вот вопрос как этот How to retrieve the visible part of a SurfaceView in Android сделать любой есть решение.

Я хочу достичь этого по этой строке ThumbnailUtils.extractThumbnail(source, newWidth, newHeight); и этой строкой я получаю изображение src как описано на диаграмме.

Что менять в этой строке точно ????

enter image description here

+0

Опубликовать снимок изображений, которые вы видите – Prem

+0

Сделано! пожалуйста, проверьте обновленное сообщение –

+0

невероятно простое решение: http://stackoverflow.com/a/17733530/294884 – Fattie

ответ

0

@Akanksha Пожалуйста, используйте этот код, приведенный ниже, вам просто нужно пройти путь сохраняемого изображения, а высота и ширина нашего ImageView. Этот код отлично работает для меня.


    import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 

public class ImageHandler { 
    /** 
    * Decode and sample down a bitmap from a file to the requested width and 
    * height. 
    * 
    * @param filename 
    *   The full path of the file to decode 
    * @param reqWidth 
    *   The requested width of the resulting bitmap 
    * @param reqHeight 
    *   The requested height of the resulting bitmap 
    * @return A bitmap sampled down from the original with the same aspect 
    *   ratio and dimensions that are equal to or greater than the 
    *   requested width and height 
    */ 


public static Bitmap decodeSampledBitmapFromFile(String filename, 
      int reqWidth, int reqHeight) { 

     // First decode with inJustDecodeBounds=true to check dimensions 
     final BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(filename, options); 

     // Calculate inSampleSize 
     options.inSampleSize = calculateInSampleSize(options, reqWidth, 
       reqHeight); 

     // Decode bitmap with inSampleSize set 
     options.inJustDecodeBounds = false; 
     return BitmapFactory.decodeFile(filename, options); 
    } 



public static int calculateInSampleSize(BitmapFactory.Options options, 
      int reqWidth, int reqHeight) { 
     // Raw height and width of image 
     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); 
      } 

      // This offers some additional logic in case the image has a 
      // strange 
      // aspect ratio. For example, a panorama may have a much larger 
      // width than height. In these cases the total pixels might 
      // still 
      // end up being too large to fit comfortably in memory, so we 
      // should 
      // be more aggressive with sample down the image (=larger 
      // inSampleSize). 

      final float totalPixels = width * height; 

      // Anything more than 2x the requested pixels we'll sample down 
      // further. 
      final float totalReqPixelsCap = reqWidth * reqHeight * 2; 

      while (totalPixels/(inSampleSize * inSampleSize) > totalReqPixelsCap) { 
       inSampleSize++; 
      } 
     } 
     return inSampleSize; 
    } 
} 

Я называю этот метод внутри асинхронной задачи, так как это может занять слишком много UImemory и время Вот как я это называю.


class Asyncing extends AsyncTask { 

     private int reqWidth; 
     private int reqHeight; 
     private ImageView iv; 
     private String fileName; 
     private ProgressDialog pd; 

     public Asyncing(int reqWidth, int reqHeight, ImageView iv, 
       String fileName) { 
      super(); 
      this.reqWidth = reqWidth; 
      this.reqHeight = reqHeight; 
      this.fileName = fileName; 
      this.iv = iv; 
     } 

     @Override 
     protected Bitmap doInBackground(String... params) { 
      return ImageHandler.decodeSampledBitmapFromFile(params[0], 
        reqWidth, reqHeight); 

     } 

     @Override 
     protected void onPostExecute(Bitmap result) { 
      iv.setImageBitmap(result); 
      if (pd.isShowing()) { 
       pd.setMessage(getString(R.string.completed)); 
       pd.dismiss(); 
      } 

      super.onPostExecute(result); 
     } 

     @Override 
     protected void onProgressUpdate(Void... values) { 

      super.onProgressUpdate(values); 
     } 

     @Override 
     protected void onPreExecute() { 
      pd = ProgressDialog.show(CustomerDetailsActivity.this, "", 
        getString(R.string.processing_signature)); 
      super.onPreExecute(); 
     } 

    } 

Это, как вы должны назвать AsyncTask


signedImagePath = data.getExtras().getString("imagePath"); 

      new Asyncing(signature_img.getWidth(), signature_img.getHeight(), 
        signature_img, "spenTest.png").execute(signedImagePath); 

выше код написан в соответствии с моими требованиями, вы измените его в соответствии с вашими.

+0

Здесь signedImagePath - это путь к вашему файлу изображения, а проведенный est.png - это имя файла изображения. –

0

Центр обрезки изображения может помочь вам это.

public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) { 
    int sourceWidth = source.getWidth(); 
    int sourceHeight = source.getHeight(); 

    // Compute the scaling factors to fit the new height and width, respectively. 
    // To cover the final image, the final scaling will be the bigger 
    // of these two. 
    float xScale = (float) newWidth/sourceWidth; 
    float yScale = (float) newHeight/sourceHeight; 
    float scale = Math.max(xScale, yScale); 

    // Now get the size of the source bitmap when scaled 
    float scaledWidth = scale * sourceWidth; 
    float scaledHeight = scale * sourceHeight; 

    // Let's find out the upper left coordinates if the scaled bitmap 
    // should be centered in the new size give by the parameters 
    float left = (newWidth - scaledWidth)/2; 
    float top = (newHeight - scaledHeight)/2; 

    // The target rectangle for the new, scaled version of the source bitmap will now 
    // be 
    RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight); 

    // Finally, we create a new bitmap of the specified size and draw our new, 
    // scaled bitmap onto it. 
    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig()); 
    Canvas canvas = new Canvas(dest); 
    canvas.drawBitmap(source, null, targetRect, null); 

    return dest; 
} 
Смежные вопросы