【问题标题】:Can I use getDrawable() with images from the gallery我可以将 getDrawable() 与图库中的图像一起使用吗
【发布时间】:2017-03-29 12:28:42
【问题描述】:

我正在编写一个 android 应用程序,其中两个设备必须通过 tcp 交换来自画廊的图像。我的问题是,要使用 getDrawable(),我的图像必须在 Drawable 文件夹中吗?或者我可以对手机图库中的图像使用该方法?提前感谢您的旅游帮助。如果问题太愚蠢或太明显,请多多包涵,我只是一个新手。

【问题讨论】:

  • ImageView imageView=(ImageView)findViewById(R.id.imageUpload);位图 bmp=((BitmapDrawable)imageUpload.getDrawable()).getBitmap();
  • 请看下面我的回答。希望能帮助你理解。

标签: android image tcp


【解决方案1】:
  1. 如果您想使用来自Drawable 文件夹的图像,请使用ContextCompat.getDrawable()

    ImageView imageView = (ImageView)findViewById(R.id.imageUpload);
    imageView.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.IMAGE_NAME));
    
  2. 如果您想从图库中挑选和使用图片,请使用IntentACTION_PICK

    Intent intent = new Intent(Intent.ACTION_PICK);
    intent .setType("image/*");
    startActivityForResult(intent , REQUEST_CODE);
    
  3. 您将在onActivityResult() 方法中从Intent 获得图像路径imageUri。最后用imageView.setImageBitmap()ImageView上显示bitmap

    @Override
    protected void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);
    
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                try {
                    final Uri imageUri = data.getData();
                    final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
    
                    imageView.setImageBitmap(selectedImage);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
    
            }
        } 
    }
    

别忘了在AndroidManifest.xml添加权限。

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

更新:

要通过TCP 发送图像,请将您的bitmap 转换为byte array 并使用SOCKETDataOutputStream 发送:

.................
.........................
Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
selectedImage.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); 
byte[] array = bos.toByteArray();

OutputStream out = socket.getOutputStream(); 
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(array.length);
dos.write(array, 0, array.length);
............
...................

仅供参考,如果您想从imageView 获取bitmap。试试这个:

//Get bitmap from imageView 
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

详情:Send Image over TCP in android applications

希望对您有所帮助~

【讨论】:

  • 感谢您的回复,我真正想要对图像做的是通过 tcp 发送它。当我使用您提供的第二个和第三个解决方案时,我无法做到。
  • @Melo:要通过TCP 发送图像,请将您的bitmap 转换为byte array 并使用SOCKETDataOutputStream 发送。请检查我的更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
  • 2016-09-06
  • 2020-11-05
相关资源
最近更新 更多