2017-05-14 58 views
-1

這是我在ImageView中存儲圖像的代碼,但我想將圖像名稱存儲在My TextView對象中請幫助如何執行此操作。在文本視圖中存儲圖像名稱

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

     if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { 

      filePath = data.getData(); 
      try { 

       bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); 
       imageView.setImageBitmap(bitmap); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    public String getStringImage(Bitmap bmp){ 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
     byte[] imageBytes = baos.toByteArray(); 
     String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); 
     return encodedImage; 
    } 

MainActivity.java 

public class MainActivity extends AppCompatActivity implements View.OnClickListener{ 


    public static final String UPLOAD_URL = "http://192.168.1.101:8080/ImageUpload/upload2.php"; 
    public static final String UPLOAD_KEY = "image"; 
    public static final String TAG = "MY MESSAGE"; 

    private int PICK_IMAGE_REQUEST = 1; 

    private Button buttonChoose; 
    private Button buttonUpload; 
    private Button buttonView; 


    private ImageView imageView; 

    private Bitmap bitmap; 

    //private Uri filePath; 
    private static Uri filePath; 
    private TextView tv1; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     buttonChoose = (Button) findViewById(R.id.buttonChoose); 
     buttonUpload = (Button) findViewById(R.id.buttonUpload); 
     buttonView = (Button) findViewById(R.id.buttonViewImage); 

     imageView = (ImageView) findViewById(R.id.imageView); 
     tv1 = (TextView)findViewById(R.id.textView); 

     buttonChoose.setOnClickListener(this); 
     buttonUpload.setOnClickListener(this); 
    } 

    private void showFileChooser() { 
     Intent intent = new Intent(); 
     intent.setType("image/*"); 
     intent.setAction(Intent.ACTION_GET_CONTENT); 
     startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); 
    } 

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

     if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { 

      filePath = data.getData(); 
      try { 

       bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); 
       imageView.setImageBitmap(bitmap); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    public String getStringImage(Bitmap bmp){ 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
     byte[] imageBytes = baos.toByteArray(); 
     String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); 
     return encodedImage; 
    } 

    private void uploadImage(){ 
     class UploadImage extends AsyncTask<Bitmap,Void,String> { 

      ProgressDialog loading; 
      RequestHandler rh = new RequestHandler(); 

      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       loading = ProgressDialog.show(MainActivity.this, "Uploading Image", "Please wait...",true,true); 
      } 

      @Override 
      protected void onPostExecute(String s) { 
       super.onPostExecute(s); 
       loading.dismiss(); 
       Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show(); 
      } 

      @Override 
      protected String doInBackground(Bitmap... params) { 
       Bitmap bitmap = params[0]; 
       String uploadImage = getStringImage(bitmap); 

       HashMap<String,String> data = new HashMap<>(); 
       data.put(UPLOAD_KEY, uploadImage); 

       String result = rh.sendPostRequest(UPLOAD_URL,data); 

       return result; 
      } 
     } 

     UploadImage ui = new UploadImage(); 
     ui.execute(bitmap); 
    } 

    @Override 
    public void onClick(View v) { 
     if (v == buttonChoose) { 
      showFileChooser(); 
     } 
     if(v == buttonUpload){ 
      uploadImage(); 
     } 
    } 
    } 

RequestHandler.java

public class RequestHandler { 

    public String sendGetRequest(String uri) { 
     try { 
      URL url = new URL(uri); 
      HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream())); 

      String result; 

      StringBuilder sb = new StringBuilder(); 

      while((result = bufferedReader.readLine())!=null){ 
       sb.append(result); 
      } 

      return sb.toString(); 
     } catch (Exception e) { 
      return null; 
     } 
    } 

    public String sendPostRequest(String requestURL, 
            HashMap<String, String> postDataParams) { 

     URL url; 
     String response = ""; 
     try { 
      url = new URL(requestURL); 

      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setReadTimeout(15000); 
      conn.setConnectTimeout(15000); 
      conn.setRequestMethod("POST"); 
      conn.setDoInput(true); 
      conn.setDoOutput(true); 


      OutputStream os = conn.getOutputStream(); 
      BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8")); 
      writer.write(getPostDataString(postDataParams)); 

      writer.flush(); 
      writer.close(); 
      os.close(); 
      int responseCode = conn.getResponseCode(); 

      if (responseCode == HttpsURLConnection.HTTP_OK) { 
       BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
       response = br.readLine(); 
      } else { 
       response = "Error Registering"; 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return response; 
    } 

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { 
     StringBuilder result = new StringBuilder(); 
     boolean first = true; 
     for (Map.Entry<String, String> entry : params.entrySet()) { 
      if (first) 
       first = false; 
      else 
       result.append("&"); 

      result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); 
      result.append("="); 
      result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); 
     } 

     return result.toString(); 
    } 
} 

enter image description here

當我選擇文件就帶我去畫廊從這裏開始選擇圖像文件,我想點擊,當我選擇圖像的名稱圖像顯示在我的textview請描述我如何做到這一點。

+0

你是什麼意思的'圖像名稱'? –

+0

感謝回覆Hamid Reza,Button ImageView這是我上傳圖像到服務器的當前佈局但是現在我想在此佈局中將圖像上傳到服務器Button TextView,所以要完成此操作,我希望在TextView中選擇圖像的引用。 –

+0

因此,只需將'filePath'和'encodedImage'存儲在靜態對象內並在任何地方使用它! –

回答

0

下面的代碼試試,希望它爲你工作

您可以使用下面的代碼從URI獲取文件名:

File file = getFile(context,filePath); 
String imageName = file.getName(); 
TextView.setText(imageName); 

這裏是的GetFile功能,

public static File getFile(Context context, Uri uri) { 
     if (uri != null) { 
      String path = getPath(context, uri); 
      if (path != null && isLocal(path)) { 
       return new File(path); 
      } 
     } 
     return null; 
    } 
0

從你的問題我解釋你想要的圖像名稱,所以這裏是一個代碼從你有的路徑獲取圖像名稱。 相反,您可以將所有圖像名稱和路徑存儲在單獨的散列映射中,並可稍後使用相應的圖像路徑獲取任何圖像名稱。

public static String getImages(Context context) { 
       Uri uri; 
       Cursor cursor; 
       int column_index_data, column_index_file_name; 
       String PathOfImage = null; 
       uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 

       String[] projection = { MediaStore.MediaColumns.DATA, 
         MediaStore.MediaColumns.TITLE }; 
       //get you a cursor with which you can search all images in your device 
       cursor = context.getContentResolver().query(uri, projection, null, 
         null, null); 
       //get the column index of the Path of the image 
       column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); 
       //get the column index of the name of the image 
       column_index_file_name = cursor 
         .getColumnIndexOrThrow(MediaStore.MediaColumns.TITLE); 
       while (cursor.moveToNext()) { 
        PathOfImage = cursor.getString(column_index_data); 
        String name = cursor.getString(column_index_file_name); 
        Log.e("Manojit",PathOfImage+"\n"+name); 

        if(PathOfImage.equals(filepath)){ 
    //here you will get the title of the image 
    //from the result set the content of the Textview 
         return cursor.getString(column_index_file_name);} 
       } 
       return null; 
      } 
+0

我用你的代碼在TextView中顯示圖像名稱,但它不工作。 –

+0

我打算分享我的活動和XML文件,請檢查並給我解決方案.Manojit Paul –

+0

如果您正在工作的圖像在您的設備中,那麼此代碼將工作。 –

相關問題