【问题标题】:How to display image from sql database to listview in android xamarin using webservices and json?如何使用 webservices 和 json 在 android xamarin 中将图像从 sql 数据库显示到 listview?
【发布时间】:2017-03-22 13:04:14
【问题描述】:

如何使用 webservices 和 json 将 sql 数据库中的图像显示到 android xamarin 中的 listview?

public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var item = objList[position];

        if (convertView == null)
        {
            convertView = objActivity.LayoutInflater.Inflate(Resource.Layout.ContListViewHospName, null);
        }
        convertView.FindViewById<TextView>(Resource.Id.tvHospID).Text = item.HospID;
        convertView.FindViewById<TextView>(Resource.Id.tvHospName).Text = item.HospName;

        byte[] img = (byte[])item.HospLogo;

        Bitmap bitmap = BitmapFactory.DecodeByteArray(item.HospLogo, 0, item.HospLogo.Length);

        convertView.FindViewById<ImageView>(Resource.Id.imgLogo).SetImageBitmap(bitmap);
        return convertView;
    }

【问题讨论】:

    标签: android asp.net xamarin


    【解决方案1】:

    我将二进制值存储在一个字符串变量中,然后我使用 json 将值传输到我的 android 项目中的 cs 文件

    您在一个字符串中存储二进制值应如下所示:"iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAABHNCSVQICAgIfAhkiAAAIABJREFUeJzsvfd33EiW7/mJgEtHb0WKFGWqSuW96epqM9P9+s30mZ/2j33n7O7Zt/Nme8zr6emu6i5fk........"

    这是base64字节。您不能只使用(byte[])string 转换为byte[]

    你需要使用System.Convert.FromBase64String()函数。

    //The string is download form server in the json file
    string myBytes = "iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAABHNCSVQICAgIfAhkiAAAIABJREFUeJzsvfd33EiW7/mJgEtHb0WKFGWqS........"
    byte[] decByte3 = System.Convert.FromBase64String(myBytes);
    

    然后将字节转换为图像:

      public Bitmap Bytes2Bimap(byte[] b)
        {
            if (b.Length != 0)
            {
                return BitmapFactory.DecodeByteArray(b, 0, b.Length);
            }
            else
            {
              return null;
            }
        }
    

    并将位图转换为可绘制的:

    Bitmap myIcon = Bytes2Bimap(decByte3);
    Drawable myIconD = new BitmapDrawable(myIcon);
    imageView1.Background = myIconD;
    

    【讨论】:

    • 非常感谢您的开发人员.. 这对我有用.. 经过三天的研究,这段代码让我得到了结果.. 非常感谢。
    【解决方案2】:

    可能是你的图片太大了尝试缩放它,比如here

    还要确保您在布局中设置了适当的尺寸,例如宽度和高度。

    【讨论】:

    • 我在数据库中的图像设置为 100px X 100px png 格式,问题是当我通过 sql server 数据库从数据库中获取图像时,我将二进制值存储在一个字符串变量中,然后我使用 json 将值传输到我的 android 项目中的 cs 文件。现在在 cs 文件中,当我获取图像的值时,它现在以 System.Byte[] 格式显示,如果我将它存储在 byte[] 变量中,它只会在我使用类型转换时允许我。现在,当我尝试将此字节 [] 转换为位图以设置为 imageView 时,它给了我错误。这是我的主要问题。提前致谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多