2017-11-08 8 views
0

Ich habe die Kamera läuft und speichern Sie das Bild auf meinem Handy, aber ich möchte jetzt in einem ImageView anzeigen, die ich eingerichtet habe, und dann noch einmal jedes Mal, wenn die App danach gestartet wird. Irgendwelche Vorschläge, wie ich das, was ich bereits erreicht habe, erweitern kann?Wie wird das zuletzt gespeicherte Bild an ImageView gesendet?

Meine Kamera-Code ist wie folgt:

private void takePic() { 
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
    File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
    String pictureName = "Avatar.jpg"; 
    File imageFile = new File(pictureDirectory, pictureName); 
    Uri pictureUri = Uri.fromFile(imageFile); 
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri); 
    startActivityForResult(cameraIntent, CAMERA_REQUEST); 
} 

Und ich habe eine Schaltfläche, die einfach auf takePic() aufruft. Ich hatte ein onActivityResult() davor sah wie folgt aus:

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { 
     Bitmap photo = (Bitmap) data.getExtras().get("data"); 
     AvatarMe.setImageBitmap(photo); 
    } 
} 

ich diese verwendet, um einfach in meinem Image die Vorschau angezeigt werden, aber wenn ich den Code modifiziert, um das Bild zu speichern Ich hatte es zu entfernen, da sonst die App würde abstürzen . Es sieht so aus, als würde Android mich nicht beides tun lassen, also brauche ich Hilfe, um herauszufinden, wie ich das machen kann.

Also im Grunde möchte ich ein Bild machen, es in meinem ImageView anzeigen und speichern, so dass, wenn die App getötet wird, nachdem das Bild aufgenommen wurde ich nur das ImageView mit dem gespeicherten Bild füllen kann.

Antwort

0

Sie können es mit picasso Bibliothek tun.

+0

sollte dies kommentieren –

+0

ja meinen Ruf 50 auch für einen Kommentar Mann :) –

+1

ok Mann sein muss, sind Sie hier richtig –

0

In Ihrem onActivityResult() Daten kommen von Absicht, aber Sie müssen in internen Speicher speichern und in Bildansicht anzeigen, haben Sie schauen.

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) 
{ 
if (resultCode == Activity.RESULT_OK) 
{ 
    Bitmap bmp = (Bitmap)data.getExtras().get("data"); 
    ByteArrayOutputStream stream = new ByteArrayOutputStream(); 

    bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); 
    byte[] byteArray = stream.toByteArray(); 

    //saving image into internal storage 

    File myfile = new File(Environment.getExternalStorageDirectory(),"yourfilename.jpg"); 

    FileOutputStream fo; 
    try { 
     myfile.createNewFile(); 
     fo = new FileOutputStream(myfile); 
     fo.write(byteArray); 
     fo.flush(); 
     fo.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    // convert byte array to Bitmap 

    Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, 
      byteArray.length); 

    imageView.setImageBitmap(bitmap); 

} 
} 
} 

Glückliche Kodierung !!

0

können Sie picasso library oder Sie können mein Ansatz, den ich verwenden, dass tha Bild komprimieren und diese imagecompression Klasse `

private Context context; 
float maxHeight; 
float maxWidth; 
boolean wantSave; 

public ImageCompression(Context context) { 
    this.context = context; 
} 

public ImageCompression(Context context, float maxHeight, float maxWidth, boolean wantSave) { 
    this.context = context; 
    this.maxHeight = maxHeight; 
    this.maxWidth = maxWidth; 
    this.wantSave = wantSave; 
} 

@Override 
protected Bitmap doInBackground(String... strings) { 
    if (strings.length == 0 || strings[0] == null) 
     return null; 

    return compressImage(strings[0]); 
} 

protected void onPostExecute(Bitmap imagePath) { 
    // imagePath is path of new compressed image. 
} 


public Bitmap compressImage(String imagePath) { 
    // to check if image is exist or not 
    File checkFile = new File(imagePath); 
    if (!checkFile.exists()) { 
     return null; 
    } 

    Bitmap scaledBitmap = null; 
    BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    Bitmap bmp = BitmapFactory.decodeFile(imagePath, options); 

    int actualHeight = options.outHeight; 
    int actualWidth = options.outWidth; 

    float imgRatio = (float) actualWidth/(float) actualHeight; 
    float maxRatio = maxWidth/maxHeight; 

    if (actualHeight > maxHeight || actualWidth > maxWidth) { 
     if (imgRatio < maxRatio) { 
      imgRatio = maxHeight/actualHeight; 
      actualWidth = (int) (imgRatio * actualWidth); 
      actualHeight = (int) maxHeight; 
     } else if (imgRatio > maxRatio) { 
      imgRatio = maxWidth/actualWidth; 
      actualHeight = (int) (imgRatio * actualHeight); 
      actualWidth = (int) maxWidth; 
     } else { 
      actualHeight = (int) maxHeight; 
      actualWidth = (int) maxWidth; 

     } 
    } 

    options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight); 
    options.inJustDecodeBounds = false; 
    options.inDither = false; 
    options.inPurgeable = true; 
    options.inInputShareable = true; 
    options.inTempStorage = new byte[16 * 1024]; 

    try { 
     bmp = BitmapFactory.decodeFile(imagePath, options); 
     scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.RGB_565); 

     float ratioX = actualWidth/(float) options.outWidth; 
     float ratioY = actualHeight/(float) options.outHeight; 
     float middleX = actualWidth/2.0f; 
     float middleY = actualHeight/2.0f; 

     Matrix scaleMatrix = new Matrix(); 
     scaleMatrix.setScale(ratioX, ratioY, middleX, middleY); 

     Canvas canvas = new Canvas(scaledBitmap); 
     canvas.setMatrix(scaleMatrix); 

     if (bmp != null) { 
      canvas.drawBitmap(bmp, middleX - bmp.getWidth()/2, middleY - bmp.getHeight()/2, new Paint(Paint.FILTER_BITMAP_FLAG)); 
      bmp.recycle(); 
     } 

     ExifInterface exif; 
     try { 
      exif = new ExifInterface(imagePath); 
      int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0); 
      Matrix matrix = new Matrix(); 
      if (orientation == 6) { 
       matrix.postRotate(90); 
      } else if (orientation == 3) { 
       matrix.postRotate(180); 
      } else if (orientation == 8) { 
       matrix.postRotate(270); 
      } 
      scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     // these lines from 144 to 157 for save the new photo 
     if (wantSave) { 
      FileOutputStream out = null; 
      String filepath = imagePath; 
      try { 
       out = new FileOutputStream(filepath); 

       //write the compressed bitmap at the destination specified by filename. 
       scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); 

      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 
     } 

     return scaledBitmap; 

    } catch (OutOfMemoryError exception) { 
     exception.printStackTrace(); 
    } 
    return null; 
} 

public static 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) { 
     final int heightRatio = Math.round((float) height/(float) reqHeight); 
     final int widthRatio = Math.round((float) width/(float) reqWidth); 
     inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; 
    } 
    final float totalPixels = width * height; 
    final float totalReqPixelsCap = reqWidth * reqHeight * 2; 

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

}

dann in onActivityResult Anruf

ImageCompression imageCompression = new ImageCompression(context, imageHeight, imageHeight, false) { 
     @Override 
     protected void onPostExecute(Bitmap bitmab) { 
      super.onPostExecute(bitmab); 
       try { 
        if (imagePath != null) { 
         mCropImageView.setImageBitmap(bitmab); 
        } 
       } catch (OutOfMemoryError error) { 
        Toast.makeText(CropImageActivity.this, "OutOfMemory, no space", Toast.LENGTH_SHORT).show(); 
       } 
     } 
    }; 
    imageCompression.execute(imagePath); 

i hoffe das hilft

0

T Die "Daten" aus der Kameraabsicht sind in diesem Fall null. Sie können dies überprüfen answer.

Um dieses Problem zu lösen, müssen Sie die URI, die Sie an die Kamera übergeben haben, global festlegen.

//make this a global variable 
Uri pictureUri = Uri.fromFile(imageFile); 

dann können Sie das Bitmap wie diese

Zugriff
void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (resultCode == RESULT_OK) 
     { 
      Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), pictureUri); 
      AvatarMe.setImageBitmap(bitmap); 
     } 
    } 

können Sie auch die pictureUri speichern eine db oder geteilt bevorzugt verwendet und später wiederverwenden.

+0

Nach versuchen Einwickeln/fangen um 'Bitmap = MediaStore.Images.Media.getBitmap (dies .getContentResolver(), BildUri); ' und ein Toast im Fang, aber es scheint etwas schief geht, als der Toast auslöst. Ich habe versucht, Uri als eine globale Variable zu definieren, wie Sie sagten, indem Sie es als 'Uri pictureUri;' definieren und dann 'pictureUri = uri.fromFile (imageFile); 'in der Methode. – PQuix

+0

Drucken Sie den Fehler im Catch-Block und lassen Sie es mich wissen .. Vielleicht kann ich Ihnen helfen – amarok

+0

Ist das, wonach Sie suchen? https://pastebin.com/5bKHYx6y – PQuix

Verwandte Themen