I have a byte[] that contains all the data that represents an image. How do I serve it out as an actual Image in a browser ? The following code returns just a list of bytes:-
List<HubAsset> hubAsset = _core.GetHubAssets(query);
byte[] file = Convert.FromBase64String(hubAsset[0].Data);
return file;
This has been on SO already:
Streaming byte[] to Image in ASP.NET C#
Related
I am developing an Android App using Xamarin Studio in order to capture a picture and then send it to a web service.
The steps are:
Capture the picture and store it on the phone.
The web service receives an object as argument. This object contains the image in Base64. This is achieved in the following line:
oImagenFace.ImagenDocumento =(string)Base64ToBitmapDrawableConverter.ConvertBack(BitmapFactory.DecodeFile (imagepath));
At this point I am getting an Out of Memory Exception, but I can not resize the image (as explained here http://developer.android.com/training/displaying-bitmaps/load-bitmap.html) because I need it with the original size. The images are about 200Kb.
Did you tried to skip the BitmapFactory.DecodeFile, and convert the whole file into Base64?
Sg. like this:
oImagenFace.ImagenDocumento =(string)Base64ToBitmapDrawableConverter.ConvertBack(imagepath);
If that won't help, I would try to read the file by chunks and convert that parts to Base64.
Upload Image on Web Server using Android / C# {Xamarin}
This is Just Small Piece of Code. it can send any image from Android to your Web
Server.
System.Net.WebClient Client = new System.Net.WebClient();
Client.Headers.Add("Content-Type", "binary/octet-stream");
byte[] result = Client.UploadFile("localhost/FolderName/upload.php", "POST", path);
string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
Here is the PHP Code {upload.php}. Create a Folder name { Uploads } in
your Application.
<?php
$uploads_dir = 'uploads/'; //Directory to save the file that comes from client application.
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
?>
In my project we need to save the image taken from webcam in a default path using flex 4.6 but giving a default path in flex(saving the image in a default path like C:\temp..) is not possible so we are passing the byte array of that captured image from flex to .ashx page in .net here,image is saving in a default path but imagebytes is not saving(showing that no data in image).If any body knows please let me know.
Finally i got the succeeded in passing the imagebytes from flex to ashx page like below
//Declare a string in script tag(Initialize a string before init() )
[Bindable]public var str64enc:String="";
//creating object for bytearray
[Bindable]public var imgbytes:ByteArray=new ByteArray();
//creating object for bitmapdata
[Bindable]public var picture1:BitmapData=new BitmapData(103,103,true);
**In your code**
var png:PNGEncoder=new PNGEncoder();
imgbytes=png.encode(picture1);
var base64enc:Base64Encoder=new Base64Encoder();
base64enc.encodeBytes(imgbytes);
str64enc=base64enc.toString();
STEP-BY-STEP PROCEDURE:-------
1-Take a base64encoder and encode the bytearray as below:
var base64enc:Base64Encoder=new Base64Encoder();
base64enc.encodeBytes(imgbytes);
2-then assign that base64 encoder object(In this case" base64enc") to string
3-In HTTPSERVICE u need to pass that string like:
<mx:HTTPService id="savepcktdata" method="POST"
url="ur's destination path like..(axis/security/security.aspx)"
result="savepcktdata_resultHandler(event)"
resultFormat="text">
<mx:request>
<Operation>savepcktdata</Operation>
<bytes>
{str64enc}
</bytes>
</mx:request>
</mx:HTTPService>
4- In .aspx page u need to retrieve like:
string str = Convert.ToString(Request.Form["bytes"]);
cocnclusion:In order to pass the image bytes from flex(flash builder 4.6) to dotnet
(visual studio) you need to pass through the base64 string like above code.
Below is the useful link related to this issue
How to pass image from a flex application to a asp net c# web service? asp-net-c-sharp-web-service
My C# program needs to display, of many possible images, one at a time. The images are on the web and I have a precise URL for each one. The program needs to either load the image from the web or, if it has been loaded previously, load it from memory/file (as the previous loading from the web should have saved it to memory/file). How do I implement this? I can get the loading from the web with a WebRequest object, but that's not enough to save it for later, faster, use.
WebRequest request = WebRequest.Create(imageURL);
Stream stream = request.GetResponse().GetResponseStream();
pictureBoxFirstPack.Image = Image.FromStream(stream);
I'm pretty sure you should be able to do this:
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
Byte[] data = ms.ToArray();
Once you have it as a Byte array you can store it in a dictionary, a database, or wherever you like really.
Use the Image.Save method to save the downloaded image (follow an example from MSDN: http://msdn.microsoft.com/en-us/library/9t4syfhh.aspx)
// Construct a bitmap from the button image resource.
Bitmap bmp1 = new Bitmap(typeof(Button), "Button.bmp");
// Save the image as a GIF.
bmp1.Save("c:\\button.gif", System.Drawing.Imaging.ImageFormat.Gif);
One of the possible ways to check if the image already exists in your local storage is to calculate the hash-sum of every downloaded image and save it inside a dictionary
SHA256Managed sha = new SHA256Managed();
byte[] checksum = sha.ComputeHash(stream);
var hash = BitConverter.ToString(checksum).Replace("-", String.Empty);
// Store hash into a dictionary
You can use the WebClient to download file like this:
string fileNameLocally = #"c:\file.jpg";
using(WebClient client = new WebClient())
{
client.DownloadFile(imageURL, fileNameLocally);
//you can also use DownloadAsyncFile this methods do not block the calling thread.
}
I am a beginner in .net Technology. I am using VS2008, C# ,Asp.Net 3.5 Framework, SQL SERVER 2005. In a database table 'Cust_M_Tbl', there is a field of varchar(500) type viz Cust_Image. The value in the Cust_Image is
mspZVnmQlz1GgRRpQEqBFGTHeUELiUhxQQ2GQU9BF3DCUYEeaiJJAQQLKGCBDYcySMENDi9qgQWJv0xBEe8sWkEEDr19QQWMxVoBE20odAEGFDtZAQeBtUtBDn7NUkEd0ytIAQl/r4WBBooWTAEHiCSGAQiMyjEBCFG+KYELYSoowQzluisBBt1NTwEYSM4hgQ5LTTpBD0e5KUEGYa0ugQxqoCLBCWgZKcEKcJJZQQ2DM1nBBAszVoEHiQMSZGhtcwEGCgwPExQUExMUFAMSYmVqcHUECQsOEBMTEhITFAISZWVobnUDCA0PERMVFRQUFRUDEWBjaG5yAQYLDg8REREREQISamlqb3UFCQ0PEhMUFRUWFhYDEV9hZmxxdQMJDQ4PEBEREQIRa2xucXcGCg0PEhMVFhgZGQQRY2ZpbXIBBgsNDxASExQDEHJzdgMHDA0PEBMVFxgZBBFiY2ZpbnMDCQsNDxIVFwMPc3YDBgkNDQ4PExQWGAQRXl9hY2ZqcwQIDBATFxgEDgQHCgwPDQ8PEhMVAxFXWFlcXV9hbXYFCxIWGRoGDA0ODwsODxMDEFVXV1dVVltkcwYOFhodAAD/Aw1PUVFQTk5RV2YKEQAA/wQMR0VFR0ZJQz0xAAD/BQdCQkMY8B0ZtKlQFCF/MssEMp7YkXe5scQP8fmd96ZVrvO8oGFXhoDAjEe5o+U/XAnxKOTp9vDgoSTOH22Eg2rytkcs9uqvFV7GSeUaetGWD0jVWeSqCuD6Sb6l/KxsWXbH1iDoY8LJhgKhkvVBei3Xmp4gx74bl58QiXckdX0KgxJhDWSa/zDvZvGfSVKVLvXzhv8/A+3tV1M36hSdkpPukozfqJj4O9ELUHNNUj8SRvFr0do7bU6tXqEbVubYYiVnalpHbCb07QoVPsO402Lwu3d9vnk6+bnZ/zbgpmAm4zfCLQrlOseeQ4XOarfqeCA14qS2EWZxATfilss++PYY+xymdxgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGA==
I want to display this customer image in my web page. How can I do it? Should I decrypt it? or it is in any other format? Any help will be appreciated. Regards,
After decoding as #Christophe Geers suggested
use
string encodedString = "your image data encoded as base 64 char array";
byte[] data = Convert.FromBase64String(encodedString);
Response.BinaryWrite(data);
maybe this can help more:
http://odetocode.com/articles/172.aspx
This looks like Base64 encoding. You can find an online decoder here:
http://en.wikipedia.org/wiki/Base64
It validates your input as a valid Base-64 char array.
You can decode a base64 string in C# in the following way:
string encodedString = "your image data encoded as base 64 char array";
byte[] data = Convert.FromBase64String(encodedString);
Take a look at the FromBase64String article on MSDN for more information.
Now you want to display the image on an ASP.NET web page (*.ASPX).
E.g.:
<img src="myimage.jpg" />
Instead of referencing an actual image file (eg: myimage.jpg), you want to reference an ASP.NET handler (*.ASHX) that serves the bytes of the image (the byte[] array named data in the previous code sample).
E.g.:
<img src="ImageHandler.ashx" />
The code for the image handler looks something like this:
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Load the image (see previous code sample)
byte[] data = ...;
// Display the image
context.Response.OutputStream.Write(data, 0, data.Length);
context.Response.ContentType = "image/JPEG";
}
}
Read more about implementing an IHttpHandler on MSDN.
You need to pass an identifier to the imagehandler.ashx page so that you know which image to retrieved.
E.g.:
<img src="ImageHandler.ashx?id=<%=id%>" />
Put this instead of your img-tag or your ASP.NET image control.
I want to output a Byte[] array to a string so I can send it along a HTTPRequest. Can it be done? And will the server pick up the data and create a file from it? Or does some special encoding need to be done?
The file is an image. At the moment I have:
Byte[] fBuff = File.ReadAllBytes("C:/pic.jpeg");
I need to take what's in fBuff and output it to send along a post request.
Use the Convert.ToBase64String method
Byte[] fBuff = File.ReadAllBytes("C:/pic.jpeg");
String base64 = Convert.ToBase64String(fBuff);
This way the string will as compact as posible and is sort of the "standard" way to writing bytes to string and back to bytes.
To convert back to bytes use Convert.FromBase64String:
String base64 = ""; // get the string
Byte[] fBuff = Convert.FromBase64String(base64);
You could just create a String where each byte is a character of the String. If you do the same opposite procedure at the receiver you will not have any problems (I have done something similar but in Java).
Convert.ToBase64String looks like your best option to store the bytes in a transmittable array, you should look into these functions.
If you are sending just the file, you can use the UploadFile method of the WebClient class:
using (WebClient client = new WebClient) {
client.UploadFile("http://site.com/ThePage.aspx", #"C:\pic.jpeg");
}
This will post the file as a regular file upload, just as from a web page with a file input. On the receiving server the file comes in the Request.Files collection.
Any reason of not using the WebClient upload file?