2016-01-04 32 views
9

Jadam lunch z zamiarem pobrania zdjęć z galerii, a ponieważ używam nexusa, to aplikacja do zdjęć Google to moja galeria, wszystko działa dobrze, ale jeśli obraz nie jest w telefonie, zdjęcie google pobierze je dla mnie tutaj jest problem po wybraniu obrazu, wysyłam obraz do innej aktywności w celu przycięcia, ale przy pobieraniu obrazu obraz jest wysyłany do aktywności zbioru zerowego, ponieważ pobieranie nie jest zakończone, ale jak mogę wiedzieć, kiedy pobieranie zostanie zakończone w celu wysłania obrazu do aktywacji upraw, jak mogę to kontrolować, tutaj jest mój kod:Pobierz zdjęcie z biblioteki zdjęć Google po pobraniu

enter code here 
private void pickFromGallery() 
{ 
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
    startActivityForResult(galleryIntent, RESULT_LOAD_IMG); 
} 
@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    try { 
     // When an Image is picked 
     if (requestCode == RESULT_LOAD_IMG && resultCode == Activity.RESULT_OK 
       && null != data) { 
      // Get the Image from data 

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

      // Get the cursor 
      Cursor cursor = getApplicationContext().getContentResolver().query(selectedImage, 
        filePathColumn, null, null, null); 
      // Move to first row 
      assert cursor != null; 
      cursor.moveToFirst(); 

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
      imgDecodableString = cursor.getString(columnIndex); 
      cursor.close(); 
      startCrop(imgDecodableString); 
     } 
    } catch (Exception e) { 
     Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG) 
       .show(); 
    } 
    } 

każda pomoc byłaby doceniana.

+0

Proszę używać kropek i przecinków, jedno długie zdanie nie jest łatwe do odczytania. –

Odpowiedz

11

Myślę, że nie można przycinaj obrazy, gdy pobierasz wybrany obraz ze zdjęć z Google. można przycinać tylko lokalne obrazy pamięci:

Ale aby sprawdzić, czy wybrany obraz jest do pobrania lub z lokalnego magazynu, możesz to zrobić w swojej metodzie onActivityResult().

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     // TODO Auto-generated method stub 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == RESULT_LOAD_IMG && resultCode == Activity.RESULT_OK 
       && null != data) { 

       Uri selectedImageUri = data.getData(); 
       String tempPath = getPath(selectedImageUri, getActivity()); 
       String url = data.getData().toString(); 
       if (url.startsWith("content://com.google.android.apps.photos.content")){ 
        try { 
         InputStream is = getActivity().getContentResolver().openInputStream(selectedImageUri); 
         if (is != null) { 
          Bitmap pictureBitmap = BitmapFactory.decodeStream(is); 
          //You can use this bitmap according to your purpose or Set bitmap to imageview 
         } 
        } catch (FileNotFoundException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
       }else { 
        startCrop(tempPath); 

      } 
     } 

} 

Oto getPath() Sposób, który jest stosowany w onActivityResult().

public String getPath(Uri uri, Activity activity) { 
    Cursor cursor = null; 
    try { 
     String[] projection = {MediaStore.MediaColumns.DATA}; 
     cursor = activity.getContentResolver().query(uri, projection, null, null, null); 
     if (cursor.moveToFirst()) { 
      int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); 
      return cursor.getString(column_index); 
     } 
    } catch (Exception e) { 
    } finally { 
     cursor.close(); 
    } 
    return ""; 
} 

Mam nadzieję, że ci to pomoże.

+0

Dzięki @Rajesh masz rację –

+0

jego wrzucenie 'FileNotFoundException' :( –

0

Możesz użyć AsyncTask do pobrania (lub skopiowania obrazu lokalnego), a następnie go przetworzyć.

W swojej działalności utworzyć:

private class PictureAsyncTask extends AsyncTask<Void, Void, String> { 
    private Uri mUri; 

    public PictureAsyncTask(Uri uri) { 
     mUri = uri; 
    } 

    @Override 
    protected String doInBackground(Void... params) { 
     InputStream inputStream = null; 
     try { 
      inputStream = getContentResolver().openInputStream(mUri); 
      String path = null; // Path of downloaded image 
      // Download image from inputStream 
      return path; 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      if (inputStream != null) { 
       try { 
        inputStream.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
     return null 
    } 

    @Override 
    protected void onPostExecute(String path) { 
     if (path == null) { 
      // Process image 
      // Maybe another AsyncTask or background thread? 
     } else { 
      // Download failed 
     } 
    } 
} 

zadzwonić z onActivityResult:

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    switch (requestCode) { 
     case RESULT_LOAD_IMG: 
      if (resultCode == RESULT_OK) { 
       if (data != null) { 
        Uri uri = data.getData(); 
        if (uri != null) { 
         new PictureAsyncTask(uri).execute(); 
        } else { 
         // No data 
        } 
       } else { 
        // No picture selected? 
       } 
      } 
      break; 
    } 
} 
+0

Chcę tylko wiedzieć, kiedy należy postępować z pobieraniem podczas używania aplikacji do zdjęć Google jako galerii –

+0

Powinieneś zawsze postępować z nią w wątku tła, nawet jeśli jest to obraz lokalny. To znaczy. zamiast pobierać możesz stworzyć bitmapę używając BitmapFactory.decodeStream (inpustStream) i przetworzyć bitmapę. To może trochę potrwać, więc nie jest dobrze, gdy robimy to w głównym wątku. –

2

nie można pobrać obrazów z Dysku Google poniżej kroki, aby pobrać obrazy lub pliki z dysku.

Aby pobrać zdjęcia lub pliku z Dysku Google, trzeba bibliotekę

  • google-API-services-drive-v2-rev9-1.8.0-beta.jar()

Konfiguracja konsolety

  • obok przejść do Google Consol

  • Utwórz nowy projekt. W sekcji Usługi musisz włączyć dwie rzeczy: DRIVE API i DRIVE SDK! Są oddzielne, jeden nie włącza automatycznie drugiego, a TY MUSISZ OBU WŁĄCZYĆ! (Wyliczyłem, że zmarnowałem co najmniej 20 godzin mojego czasu w samotności.)

  • Nadal na konsoli przejdź do API Access. Utwórz klienta, uczyń go aplikacją na Androida. Podaj mu swój identyfikator pakietu. Nie sądzę, aby odciski palców były rzeczywiście ważne, ponieważ jestem pewien, że użyłem niewłaściwego, ale mimo to staram się to naprawić (Google zapewnia instrukcje).

  • To wygeneruje Identyfikator klienta. Będziesz tego potrzebował. Trzymaj się tego.

Android CODE - Konfigurowanie i przesyłania

  • pierwsze, uzyskać token logowania:

    AccountManager am = AccountManager.get (aktywność); am.getAuthToken (am.getAccounts()) [0], "oauth2:" + DriveScopes.DRIVE, nowy pakiet(), true, nowy OnTokenAcquired(), null);

Następnie OnTokenAcquired() musi być ustawione tak:

private class OnTokenAcquired implements AccountManagerCallback<Bundle> { 
    @Override 
    public void run(AccountManagerFuture<Bundle> result) { 
     try { 
      final String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN); 
      HttpTransport httpTransport = new NetHttpTransport(); 
      JacksonFactory jsonFactory = new JacksonFactory(); 
      Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null); 
      b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() { 
       @Override 
       public void initialize(JSonHttpRequest request) throws IOException { 
        DriveRequest driveRequest = (DriveRequest) request; 
        driveRequest.setPrettyPrint(true); 
        driveRequest.setKey(CLIENT ID YOU GOT WHEN SETTING UP THE CONSOLE BEFORE YOU STARTED CODING) 
        driveRequest.setOauthToken(token); 
       } 
      }); 

      final Drive drive = b.build(); 

      final com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File(); 
      body.setTitle("My Test File"); 
    body.setDescription("A Test File"); 
    body.setMimeType("text/plain"); 

      final FileContent mediaContent = new FileContent("text/plain", an ordinary java.io.File you'd like to upload. Make it using a FileWriter or something, that's really outside the scope of this answer.) 
      new Thread(new Runnable() { 
       public void run() { 
        try { 
         com.google.api.services.drive.model.File file = drive.files().insert(body, mediaContent).execute(); 
         alreadyTriedAgain = false; // Global boolean to make sure you don't repeatedly try too many times when the server is down or your code is faulty... they'll block requests until the next day if you make 10 bad requests, I found. 
        } catch (IOException e) { 
         if (!alreadyTriedAgain) { 
          alreadyTriedAgain = true; 
          AccountManager am = AccountManager.get(activity); 
          am.invalidateAuthToken(am.getAccounts()[0].type, null); // Requires the permissions MANAGE_ACCOUNTS & USE_CREDENTIALS in the Manifest 
          am.getAuthToken (same as before...) 
         } else { 
          // Give up. Crash or log an error or whatever you want. 
         } 
        } 
       } 
      }).start(); 
      Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT); 
      if (launch != null) { 
       startActivityForResult(launch, 3025); 
       return; // Not sure why... I wrote it here for some reason. Might not actually be necessary. 
      } 
     } catch (OperationCanceledException e) { 
      // Handle it... 
     } catch (AuthenticatorException e) { 
      // Handle it... 
     } catch (IOException e) { 
      // Handle it... 
     } 
    } 
} 

Android CODE - Pobieranie

private java.io.File downloadGFileToJFolder(Drive drive, String token, File gFile, java.io.File jFolder) throws IOException { 
    if (gFile.getDownloadUrl() != null && gFile.getDownloadUrl().length() > 0) { 
     if (jFolder == null) { 
      jFolder = Environment.getExternalStorageDirectory(); 
      jFolder.mkdirs(); 
     } 
     try { 

      HttpClient client = new DefaultHttpClient(); 
      HttpGet get = new HttpGet(gFile.getDownloadUrl()); 
      get.setHeader("Authorization", "Bearer " + token); 
      HttpResponse response = client.execute(get); 

      InputStream inputStream = response.getEntity().getContent(); 
      jFolder.mkdirs(); 
      java.io.File jFile = new java.io.File(jFolder.getAbsolutePath() + "/" + getGFileName(gFile)); // getGFileName() is my own method... it just grabs originalFilename if it exists or title if it doesn't. 
      FileOutputStream fileStream = new FileOutputStream(jFile); 
      byte buffer[] = new byte[1024]; 
      int length; 
      while ((length=inputStream.read(buffer))>0) { 
       fileStream.write(buffer, 0, length); 
      } 
      fileStream.close(); 
      inputStream.close(); 
      return jFile; 
     } catch (IOException e) {   
      // Handle IOExceptions here... 
      return null; 
     } 
    } else { 
     // Handle the case where the file on Google Drive has no length here. 
     return null; 
    } 
} 
+1

W tym miejscu jest mowa o Zdjęciach Google, a nie na Dysku Google. W każdym razie - możesz pobrać plik z Dysku Google za pomocą DocumentsProvider. –

+0

@MilosFec google dysk jest częścią google i google zawsze przechowuj zdjęcia na dysku Google. –

+1

To nie ma znaczenia. Po zainstalowaniu Zdjęć Google możesz robić zdjęcia za pomocą Intent.ACTION_PICK. Jeśli masz zainstalowany Dysk Google, możesz pobrać dowolny plik, używając Intent.ACTION_OPEN_DOCUMENT. –

Powiązane problemy