【问题标题】:How to convert ImageView image to byte code by using Base64 encode?如何使用 Base64 编码将 ImageView 图像转换为字节码?
【发布时间】:2012-02-17 09:32:56
【问题描述】:

我正在处理图像。在我的应用程序中,我显示了可绘制的图像并将该可绘制图像设置为 ImageView。当我点击一个按钮时,我想使用 Base64 将 ImageView 图像编码为字节码。

我实现的代码如下:

((ImageView)findViewById(R.id.imageView1)).setImageResource(R.drawable.person);

((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        ((TextView)findViewById(R.id.textView1)).setText("Get((ImageView)findViewById(R.id.imageView1)) image Base64.encode() here");
    }
});

如何将编码后的 imageView1 图像转换为字节码?

谁能帮帮我。

【问题讨论】:

    标签: android image imageview encode


    【解决方案1】:

    试试这个...

        Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.images);
        ByteArrayOutputStream stream=new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
        byte[] image=stream.toByteArray();
        System.out.println("byte array:"+image);
    
        String img_str = Base64.encodeToString(image, 0);
        System.out.println("string:"+img_str);
    

    现在将该字符串设置为您的 Textview

        tv.setText(img_str);
    

    【讨论】:

    • 在编码为Base64时是否需要始终压缩图像?是否可以直接将图像/图像文件转换为Base64编码的字符串而不进行压缩?
    【解决方案2】:

    使用这个

    public String encode(Bitmap icon) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            icon.compress(Bitmap.CompressFormat.PNG, 50, baos);
            byte[] data = baos.toByteArray();
            String test = Base64.encodeBytes(data);
            return test;
        }`
    

    【讨论】:

    • 如何在 Bitmap 中获取 imageView1?
    • 位图图标 = BitmapFactory.decodeResource(context.getResources(), R.drawable.person);
    【解决方案3】:

    看看这段代码,

    Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.person)
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bMap .compress(Bitmap.CompressFormat.PNG, 100, baos);
    //bMap is the bitmap object
    byte[] b = baos.toByteArray(); 
    String encodedString = Base64.encodeToString(b, Base64.DEFAULT)
    

    【讨论】:

      猜你喜欢
      • 2011-04-27
      • 2020-07-25
      • 1970-01-01
      • 2020-10-26
      • 2011-11-03
      • 1970-01-01
      • 2013-08-24
      • 2015-08-21
      • 2013-03-18
      相关资源
      最近更新 更多