无法使用 C# 将类型“字符串”隐式转换为“字节[]”
本文关键字:字符串 转换 字节 类型 | 更新日期: 2023-09-27 18:36:48
对于我的项目,我需要将图像作为哈希代码获取,如下所示 28F996F0.jpg。我正在尝试以下代码来获取此值,但有一个错误 - 无法隐式将类型"字符串"转换为"byte[]"。
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
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);
}
}
这是你要找的吗?
只需修改最后一个类属性:
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());
您需要向 PoiImageAnswer 类添加一个字符串属性以包含图像 url。
public string ImageUrl { get; set; }
然后:
img.ImageUrl = string.Format("{0:X}.jpg", Image.GetHashCode());
编辑:
这将允许您将其放入 byte[]:
img.ImageData = new System.Text.UTF8Encoding().GetBytes(string.Format("{0:X}.jpg", Image.GetHashCode()));