2016-07-22 32 views
1

ich meine Bilder im internen Speicher speichern möchten, ich google gesucht und Stackoverflow, aber konnte es nicht getan, hier ist mein Code:Speichern Bild in den internen Speicher

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    imageView = (ImageView) findViewById(R.id.ss); 
    tv = (TextView) findViewById(R.id.tv); 
    // Firebase.setAndroidContext(this); 
    //Firebase ref = new Firebase(FIREBASE_URL); 

    Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
    startActivityForResult(i, RESULT_LOAD_IMAGE); 
} 



protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    super.onActivityResult(requestCode, resultCode, data); 

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) 
    { 
     Uri selectedImage = data.getData(); 
     String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

     Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); 
     cursor.moveToFirst(); 

     int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
     String picturePath = cursor.getString(columnIndex); 
     cursor.close(); 
     bitmap = BitmapFactory.decodeResource(getResources(), 
       RESULT_LOAD_IMAGE); 

     // Find the SD Card path 
     File filepath = Environment.getExternalStorageDirectory(); 

     // Create a new folder in SD Card 
     File dir = new File(filepath.getAbsolutePath() 
       + "/Save Image Tutorial/"); 
     dir.mkdirs(); 

     // Create a name for the saved image 
     File file = new File(dir, "myimage.png"); 

     // Show a toast message on successful save 
     Toast.makeText(MainActivity.this, "Image Saved to SD Card", 
       Toast.LENGTH_SHORT).show(); 
     try { 

      output = new FileOutputStream(file); 

      // Compress into png format image from 0% - 100% 
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, output); 
      output.flush(); 
      output.close(); 
     } 

     catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


    } 

     // drawView.load_pic(picturePath); 
    } 
} 

Ich möchte von ein Bild erhalten Die Galerie wird gespeichert und im internen Speicher gespeichert. In diesem Code wird jedoch nur der Name der Datei im Verzeichnis gespeichert. Wenn mir jemand helfen könnte, das zu lösen.

+0

Versuchen Sie, alle Kappen in Sätze zu vermeiden. Sie können [fragen] nachfragen, wenn Sie weitere Informationen benötigen. – HiDeo

+0

Die Universal Image Loader-Bibliothek bietet die Option, Bilder sowohl im Arbeitsspeicher als auch auf der Festplatte zwischenzuspeichern. Bitte überprüfen Sie, dass –

Antwort

0

Sie schreiben, Bilddateien auf externen Speicher

File filepath = Environment.getExternalStorageDirectory(); 

so überprüfen, ob Sie die richtige Erlaubnis in Android Manifest erwähnt haben, zu schreiben Daten auf SD-Karte

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

und erhalten auch die Bitmap ausgewählt aus Weg

Bitmap bitmap = BitmapFactory.decodeFile(picturePath); 

statt

bitmap = BitmapFactory.decodeResource(getResources(), 
      RESULT_LOAD_IMAGE); 

RESULT_LOAD_IMAGE ist Anforderungs-Code nicht id ausgewählter Bildressource

+0

, wie man das Bild vom Benutzer von der Galerie erhält und es im internen Speicher speichert, wie erhält dieser Code Bild vom Benutzer? –

+0

yeah Ich hv getan, mein Problem ist, wie man Bild vom Benutzer erhält und es im internen Speicher speichert, zum Beispiel benutze ich diesen Code, um Bild vom Benutzer zu erhalten Absicht i = neue Absicht (Intent.ACTION_PICK, android.provider.MediaStore. Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult (i, RESULT_LOAD_IMAGE); Und wie man dieses Bild im internen Speicher speichert –

+0

benutze BitmapFactory.decodeFile (picturePath); Um eine Bitmap des ausgewählten Bildes zu erhalten, ist RESULT_LOAD_IMAGE nicht die Ressourcen-ID des Bildes, das Sie ausgewählt haben. –

0

Sie können Fileoutputstream verwenden Ihre Bitmap zu speichern. Nachdem sie das Bitmap aus der Galerie, FileOutputStream out = null; try { out = new FileOutputStream("fileName"); //Enter the desired filename bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (Exception e) { e.printStackTrace(); } }

+0

Danke für die Hilfe, es funktioniert !! :) –

+0

Wenn meine Antwort half, bitte Up-Vote und markieren Sie meine Antwort. Vielen Dank –

0

OnChoose-Code

 chooseimage.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 



      if (Build.VERSION.SDK_INT >= 23){ 

       boolean result= Utility.checkPermission(getActivity()); 

       if(result) { 
        galleryIntent(); 
       } 

      } 

      else { 
       Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

       // Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery. 
       startActivityForResult(i,LOAD_IMAGE_RESULTS); //LOAD_IMAGE_RESULTS 
      } 




     } 
    }); 

Auch Runtime Erlaubnis hinzugefügt und Set Bild auf dem gewünschten Standort

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (Build.VERSION.SDK_INT >= 23) { 
     if (resultCode == Activity.RESULT_OK) { 
      if (requestCode == LOAD_IMAGE_RESULTS) { 
       onSelectFromGalleryResult(data); 

      } 
     } 
    } 
    else { 



       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) { 

        Bitmap bitmap = null; 
        Uri selectedImage = data.getData(); 
        String wholeID = DocumentsContract.getDocumentId(selectedImage); 

        // Split at colon, use second item in the array 
        String id = wholeID.split(":")[1]; 

        String[] column = {MediaStore.Images.Media.DATA}; 

        // where id is equal to 
        String sel = MediaStore.Images.Media._ID + "=?"; 

        Cursor cursor = getActivity().getContentResolver(). 
          query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
            column, sel, new String[]{id}, null); 

        String filePath = ""; 

        int columnIndex = cursor.getColumnIndex(column[0]); 

        if (cursor.moveToFirst()) { 
         //filePath = cursor.getString(columnIndex); 
         mPath = cursor.getString(columnIndex); 
        } 


        cursor.close(); 

       } 
       else { 
        if (requestCode == LOAD_IMAGE_RESULTS && resultCode == getActivity().RESULT_OK && data != null) { 
         // Let's read picked image data - its URI 
         Uri pickedImage = data.getData(); 
         // Let's read picked image path using content resolver 
         String[] filePath = {MediaStore.Images.Media.DATA}; 
         Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath, null, null, null); 
         cursor.moveToFirst(); 
         mPath = cursor.getString(cursor.getColumnIndex(filePath[0])); 
         //edAttach.setText(mPath.toString()); path set anywhere 
         cursor.close(); 
        } 

       } 
    } 
} 




private void onSelectFromGalleryResult(Intent data) { 

    Bitmap bitmap=null; 
    if (data != null) { 
     try { 
      bitmap= MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
ivprofile.setImageBitmap(bm); 
    } 



    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) { 
     Uri selectedImage = data.getData(); 
     String wholeID = DocumentsContract.getDocumentId(selectedImage); 

     // Split at colon, use second item in the array 
     String id = wholeID.split(":")[1]; 

     String[] column = {MediaStore.Images.Media.DATA}; 

     // where id is equal to 
     String sel = MediaStore.Images.Media._ID + "=?"; 

     Cursor cursor = getActivity().getContentResolver(). 
       query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
         column, sel, new String[]{id}, null); 

     String filePath = ""; 

     int columnIndex = cursor.getColumnIndex(column[0]); 

     if (cursor.moveToFirst()) { 
      //filePath = cursor.getString(columnIndex); 
      mPath = cursor.getString(columnIndex); 
      //edAttach.setText(mPath); path set anywhere 


     } 
     cursor.close(); 
    } 
    else { 
     Uri selectedImage = data.getData(); 
     String[] filePathColumn = {MediaStore.Images.Media.DATA}; 

     Cursor cursor = getActivity().getContentResolver().query(selectedImage, 
       filePathColumn, null, null, null); 
     cursor.moveToFirst(); 

     int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
     mPath = cursor.getString(columnIndex).toString(); 
     System.out.println("picturePath" + mPath); 
     if (!mPath.equalsIgnoreCase(null)) { 
      edAttach.setText(mPath); 
     } 
     cursor.close(); 


    } 


    // Your Image Copy on Your desired location 

    if(!mPath.equalsIgnoreCase("")) 
     { 
      File filepath = Environment.getExternalStorageDirectory(); 

      // Create a new folder in SD Card 
      File dir = new File(filepath.getAbsolutePath() 
        + "/"+"Save Image Tutorial"+"/"); 
      dir.mkdirs(); 

      // Create a name for the saved image 
      File file = new File(dir, "myImage.png"); 

      // Show a toast message on successful save 


      try { 

       FileOutputStream output = new FileOutputStream(file); 

       // Compress into png format image from 0% - 100% 
       bitmap.compress(Bitmap.CompressFormat.PNG, 100, output); 
       output.flush(); 
       output.close(); 


       Toast.makeText(getActivity(), "Image Saved to SD Card", 
         Toast.LENGTH_SHORT).show(); 
      } 

      catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 


} 

public boolean hasPermissionInManifest(Context context, String permissionName) { 
    final String packageName = context.getPackageName(); 
    try { 
     final PackageInfo packageInfo = context.getPackageManager() 
       .getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); 
     final String[] declaredPermisisons = packageInfo.requestedPermissions; 
     if (declaredPermisisons != null && declaredPermisisons.length > 0) { 
      for (String p : declaredPermisisons) { 
       if (p.equals(permissionName)) { 
        return true; 
       } 
      } 
     } 
    } catch (PackageManager.NameNotFoundException e) { 

    } 
    return false; 
} 


public static boolean isMediaDocument(Uri uri) 
{ 
    return "com.android.providers.media.documents".equals(uri.getAuthority()); 
} 

private void galleryIntent() 
{ 
    Intent intent = new Intent(Intent.ACTION_PICK); 
    intent.setType("image/*"); 
    intent.setAction(Intent.ACTION_GET_CONTENT);// 
    startActivityForResult(Intent.createChooser(intent, "Select File"),LOAD_IMAGE_RESULTS); 
} 
@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
    switch (requestCode) { 
     case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 


       galleryIntent(); 

      } else { 
       //code for deny 
      } 
      break; 
    } 
} 

oder Genehmigungen im Ihre mainfiest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

Utility.java

import android.Manifest; 
import android.annotation.TargetApi; 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.pm.PackageManager; 
import android.os.Build; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 

public class Utility { 
    public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123; 
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
    public static boolean checkPermission(final Context context) 
    { 
     int currentAPIVersion = Build.VERSION.SDK_INT; 
     if(currentAPIVersion>= Build.VERSION_CODES.M) 
     { 
      if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { 
       if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) { 
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context); 
        alertBuilder.setCancelable(true); 
        alertBuilder.setTitle("Permission necessary"); 
        alertBuilder.setMessage("External storage permission is necessary"); 
        alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { 
         @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
         public void onClick(DialogInterface dialog, int which) { 
          ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); 
         } 
        }); 
        AlertDialog alert = alertBuilder.create(); 
        alert.show(); 
       } else { 
        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); 
       } 
       return false; 
      } else { 
       return true; 
      } 
     } else { 
      return true; 
     } 
    } 
}