2015-07-27 2 views
0

Что я делаю?Захваченное разрешение изображения слишком велико

Я разрешаю пользователю снимать изображение, хранить его на SD-карте и загружать на сервер.

Но получить разрешение захватываемого изображения, как Ширина: 4608 пикселей и высота: 2592 пикселей

Теперь что я хочу?

Как получить изображения малого разрешения без какого-либо компромисса с качеством, как минимальное разрешение я могу получить или установить захвачена разрешение изображения 25% исходного разрешения изображения .. (Device Specific)

CameraCaptureActivity.java:

public class CameraCaptureActivity extends Activity implements OnClickListener, PictureCallback { 

    CameraSurfaceView cameraSurfaceView; 
    Button shutterButton; 
    SimpleDateFormat simpleDateFormat; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_camera_capture); 

     FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview); 
     cameraSurfaceView = new CameraSurfaceView(this); 
     preview.addView(cameraSurfaceView); 

     shutterButton = (Button) findViewById(R.id.shutter_button); 
     shutterButton.setOnClickListener(this); 
    } 


    @Override 
    public void onClick(View v) { 
     takePicture(); 
    } 

    private void takePicture() { 
     shutterButton.setEnabled(false); 
     cameraSurfaceView.takePicture(this); 
    } 

    @Override 
    public void onPictureTaken(byte[] data, Camera camera) { 
     // TODO something with the image data 

     File pictureFileDir = getDir(); 

     if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) { 
      return; 
     } 


     simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); 
     strDateFormat = simpleDateFormat.format(new Date()); 

     String photoFile = "Latest.jpg"; 

     String filename = pictureFileDir.getPath() + File.separator + photoFile; 

     File pictureFile = new File(filename); 

     try { 
      FileOutputStream fos = new FileOutputStream(pictureFile); 
      fos.write(data); 
      fos.close(); 
      Toast.makeText(CameraCaptureActivity.this, "Image saved:" + photoFile, 
        Toast.LENGTH_LONG).show(); 

      // Restart the preview and re-enable the shutter button so that we can take another picture 
      camera.stopPreview(); 
      shutterButton.setEnabled(false);   

     } catch (Exception error) {    
      Toast.makeText(CameraCaptureActivity.this, "Image could not be saved.", 
        Toast.LENGTH_LONG).show(); 
     } 
    } 

    private File getDir() { 
     File sdDir = Environment 
      .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
     return new File(sdDir, "Latest Models"); 
    } 


    public void onResume() 
    { 
     super.onResume(); 
     shutterButton.setEnabled(true); 
    } 

} 

CameraSurfaceView.java:-

class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback { 

    Camera camera; 

    CameraSurfaceView(Context context) { 
     super(context); 

     SurfaceHolder holder = this.getHolder(); 
     holder.addCallback(this); 
    } 

    @Override 
    public void surfaceChanged(SurfaceHolder holder, int format, int width, 
           int height) { 

     camera.setDisplayOrientation(90);  
     camera.startPreview(); 
    } 

    @Override 
    public void surfaceCreated(SurfaceHolder holder) { 
     try { 
      // Open the Camera in preview mode 
      this.camera = Camera.open(); 
      this.camera.setPreviewDisplay(holder); 
     } catch (IOException ioe) { 
      ioe.printStackTrace(System.out); 
     } 

    } 

    @Override 
    public void surfaceDestroyed(SurfaceHolder holder) {    
     camera.stopPreview(); 
     camera.release(); 
     camera = null; 
    } 

    @Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) { 
     // TODO Auto-generated method stub 
    } 

    public void takePicture(PictureCallback imageCallback) { 
     camera.takePicture(null, null, imageCallback); 
    } 

} 
+0

использовать поиск e ngine ans ищите «java resize image» и пытайтесь реализовать его самостоятельно. если вы столкнулись с проблемами, вернитесь с ними сюда. – hoijui

+0

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html –

ответ

0

Try ниже кода, он может помочь вам

сначала преобразовать изображение с требуемой высотой и шириной

public static Bitmap scaleImage(String p_path, int p_reqHeight, int p_reqWidth) throws Throwable 
{ 
    Bitmap m_bitMap = null; 
    System.gc(); 
    File m_file = new File(p_path); 
    if (m_file.exists()) 
    { 
     BitmapFactory.Options m_bitMapFactoryOptions = new BitmapFactory.Options(); 
     m_bitMapFactoryOptions.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(m_file.getPath(), m_bitMapFactoryOptions); 
     m_bitMapFactoryOptions.inSampleSize = calculateInSampleSize(m_bitMapFactoryOptions, p_reqHeight, p_reqWidth); 
     m_bitMapFactoryOptions.inJustDecodeBounds = false; 
     m_bitMap = BitmapFactory.decodeFile(m_file.getPath(), m_bitMapFactoryOptions); 
    } 
    else 
    { 
     throw new Throwable(p_path + " not found or not a valid image"); 
    } 
    return m_bitMap; 
} 


private static int calculateInSampleSize(BitmapFactory.Options p_options, int p_reqWidth, int p_reqHeight) 
{ 
    // Raw height and width of image 
    final int m_height = p_options.outHeight; 
    final int m_width = p_options.outWidth; 
    int m_inSampleSize = 1; 
    if (m_height > p_reqHeight || m_width > p_reqWidth) 
    { 
     final int m_halfHeight = m_height/2; 
     final int m_halfWidth = m_width/2; 
     // Calculate the largest inSampleSize value that is a power of 2 and keeps both 
     // height and width larger than the requested height and width. 
     while ((m_halfHeight/m_inSampleSize) > p_reqHeight && (m_halfWidth/m_inSampleSize) > p_reqWidth) 
     { 
      m_inSampleSize *= 2; 
     } 
    } 
    return m_inSampleSize; 
} 
0

использование FileOutputStream.flush() после записи данных ...

File file = new File(fileName.toString()); 
try { 
    FileOutputStream stream = new FileOutputStream(file); 
    bitmap.compress(CompressFormat.PNG, 100, stream); 
    stream.flush(); 
    stream.close(); 
} catch (Exception e) { 
    // TODO: handle exception 
} 

Вы можете сохранить растровый снимок следующий код

Bitmap photo = (Bitmap) "your Bitmap image"; 
photo = Bitmap.createScaledBitmap(photo, 100, 100, false); 
ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes); 

File f = new File(Environment.getExternalStorageDirectory() 
     + File.separator + "Imagename.jpg"); 
f.createNewFile(); 
FileOutputStream fo = new FileOutputStream(f); 
fo.write(bytes.toByteArray()); 
fo.close(); 
+0

можете ли вы рассказать мне о своем решении и где я должен поместить это в свой код? – Sophie

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