2016-02-29 97 views
0

对于我的项目,我需要将图像索引作为像这样的哈希码28F996F0.jpg。我正在尝试下面的代码来获取此值,但有一个错误 - 不能隐式地将类型'字符串'转换为'byte []'。不能隐式地使用C#将类型'字符串'转换为'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

+0

错误是告诉你到底是什么问题..你试图设置'的ImageData这类型的byte'到'string'还他们正确的语法是'public int Width {get;组; }' – MethodMan

+0

'Encoding.GetBytes'从字符串中创建一个字节数组......但我不是100%肯定的,这就是你真正想要做的。 – Haukinger

回答

2
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); 
    } 
} 

代码是不是你想找的?

+0

我想直接在我的代码中。就像我在这一行中提取图像源var Image = ImgresponseJson.query.pages [ImgfirstKey] .thumbnail.source ;.所以基本上这是网址。然后在下一行我想直接做。是否有可能 –

0

您需要为您的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())); 
+0

谢谢你的工作。因为ImageUrl是字符串格式。但如果我想保持它像字节格式,像我的代码字节[] ImageData {set;得到;无论如何,这是可能的。 –

+0

它显示错误“System.Text.Encoding.UTF8”是一个'属性',但用于'类型' –

+0

对不起,忘了放在()中。 – Kevin

0

只需修改最后的类属性:

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()); 
相关问题