I'm writing a web application which saves images from the web to a database. Currently, what I use to save images is as follows:
[WebMethod]
public static void Save(string pictures)
{
// pictures is an object containing the URL of the image along with some metadata
List<ImageObject> imageList = new JavaScriptSerializer().Deserialize<List<ImageObject>>(pictures);
for (int i = 0; i < imageList.Count; i++)
{
var webClient = new WebClient();
byte[] byteArray = webClient.DownloadData(imageList[i].URL);
imageList[i].Picture = byteArray;
}
// some SQL to save imageList
}
ImageObject:
[DataContract]
public class ImageObject
{
[DataMember]
public string URL { get; set; }
[DataMember]
public string Picture { get; set; }
}
Now, this works just fine for downloading from a URL. The entry saved to my database:
0xFFD8FFE000104A464946000101[...]331B7CCA7F0AD3A02DC8898F
To display this image, I simply callSystem.Convert.ToBase64String()
after retrieving it and use it as an imagesrc
. However, I am now trying to add some functionality for users to upload their own pictures. My function for this, called from an<input />
:
function uploadPicture(){
var numPics = document.getElementById("uploadedPictures").files.length;
var oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
var src = oFREvent.target.result;
document.getElementById('image').src = src;
}
oFReader.readAsDataURL(document.getElementById("uploadedPictures").files.length;
}
When using this, this is the image source I get from the browser (over 2 MB when the original is only ~500 KB):
data:image/bmp;base64,/9j/4AAQSkZJRgABAgEAY[...]k8tTMZEBCsEbSeRYem493IHAfiHWq6vKlOv/Z
This gets displayed properly when used as a source. However, since this is not an actual URL (andWebClient.DownloadData()
is restricted to URLs of < 260 characters), I have been trying other methods to save this data into my database. However, I cannot seem to find a function to save it in the same format asWebClient.DownloadData()
. For example, I have looked at converting a base 64 string to an image and saving it, where most of the answers seem to useConvert.FromBase64String()
, but using this appears to save in a different format to my database:
0x64006100740061003A0069006D0[...]10051004500420041005100450042004
Trying to useSystem.Convert.ToBase64String()
on this returns
ZABhAHQAYQA6AGkAbQBhAGcAZQAvAGIAbQBwADsAYgBh[...]UwBlAFIAWQBlAG0ANAA5ADMASQBIAEEAZgBpAEgAVwBxADYAdgBLAGwATwB2AC8AWgA=
which is different from what I usedConvert.FromBase64String()
on. Other things I found on Google to try and get it to save in the same format or display as an image have not worked thus far.
Hence, I am wondering whether there exists a method to convert the result from aFileReader
to the same format asWebClient.DownloadData()
does for URLs or if there is some way to convert the0x6400[...]
data to a format that can be displayed by using it as an<img>
source.