【问题标题】:Cannot implicitly convert type 'string' to 'byte[]' using C#无法使用 C# 将类型“字符串”隐式转换为“字节 []”
【发布时间】:2016-06-12 18:49:43
【问题描述】:

对于我的项目,我需要将图像源作为哈希码,例如 28F996F0.jpg。我正在尝试以下代码来获取此值,但有一个错误-无法将类型“字符串”隐式转换为“字节 []”。

 var Image= ImgresponseJson.query.pages[ImgfirstKey].thumbnail.source;
 img.ImageData = string.Format("{0:X}.jpg", Image.GetHashCode());

我的 Json 对象类是

public class PoiImageAnswer
{
 public int Width { set; get; }
 public int Height { set; get; }
 public byte[] ImageData { set; get; }
}

我不知道如何将图像 url 转换为像这样 28F996F0.jpg 的哈希码

【问题讨论】:

  • 错误告诉你问题出在哪里。你试图将ImageData which is of type byte设置为string,它们的正确语法是public int Width { get; set; }
  • Encoding.GetBytes 从一个字符串创建一个字节数组......但我不是 100% 确定,这就是你真正想要做的。

标签: c# hashcode gethashcode imageurl


【解决方案1】:
public class Hash
{
    public static string GetHash(string input)
    {
        HashAlgorithm hashAlgorithm = new SHA256CryptoServiceProvider();
        byte[] byteValue = Encoding.UTF8.GetBytes(input);
        byte[] byteHash = hashAlgorithm.ComputeHash(byteValue);
        return Convert.ToBase64String(byteHash);
    }
}

这是你要找的吗?

【讨论】:

  • 我想直接在我的代码中。就像我在这一行中提取图像源 var Image= ImgresponseJson.query.pages[ImgfirstKey].thumbnail.source;。所以基本上这是网址。然后在下一行我想直接做。有没有可能
【解决方案2】:

只需修改最后一个类属性:

public class PoiImageAnswer
{
 public int Width { set; get; }
 public int Height { set; get; }
 public string ImageDataFilename { set; get; }
}

那么你的代码就可以工作了:

string ImageURL = "http://kajsdkajdg.com/abc.jpg";
var ImageURLHash = string.Format("{0:X}.jpg", ImageURL.GetHashCode());

【讨论】:

    【解决方案3】:

    您需要在 PoiImageAnswer 类中添加一个字符串属性以包含图像 url。例如

    public string ImageUrl { get; set; }
    

    然后:

    img.ImageUrl = string.Format("{0:X}.jpg", Image.GetHashCode());
    

    编辑:

    这将允许您将其放入字节[]:

    img.ImageData = new System.Text.UTF8Encoding().GetBytes(string.Format("{0:X}.jpg", Image.GetHashCode()));
    

    【讨论】:

    • 谢谢它正在工作。因为 ImageUrl 是字符串格式。但是,如果我想将其保留为字节格式,例如我的代码 byte[] ImageData { set;得到; } 有可能吗?
    • 它显示错误 'System.Text.Encoding.UTF8' 是一个 'property' 但被用作一个 'type'
    • 抱歉,忘记输入 ()。
    • @Kelvin 我试过这个。这显示了输出“ImageData”:“QzgyRTRENjguanBn”。但是我可以从这个代码中得到 28F996F0.jpg 这种类型的数字吗?
    • 你是如何试图把字符串取出来的?你必须扭转这个过程,例如var testString = new System.Text.UTF8Encoding.GetString(img.ImageData)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多