How to convert Image object to Base64 image in java? - javafx

I have an Image object created using
SnapshotParameters para = new SnapshotParameters();
para.setFill(Color.TRANSPARENT);
Image img = myStackPane.snapshot(para, null);
Now, I want to convert it to Base64 image to put it into javafx WebView. But I did not find any method to do it. Can anybody help me please?

Convert Image to byte array such as in this answer. Then use any Base64 library to encode. For example Apache Commons.
EDIT
BufferedImage bImage = SwingFXUtils.fromFXImage(logo.getImage(), null);
ByteArrayOutputStream s = new ByteArrayOutputStream();
ImageIO.write(bImage, "png", s);
byte[] res = s.toByteArray()
s.close();
Base64.encode(res);

Related

Convert Bytes to Image ASP.NET c# and use it in Image1.Url

I have a WEB-APP that is a Web-Cam App that takes images and stores into a database as bytes, Now with that being said I also don't want to save the images those are taken and save it in any kind of folder right now the only way to show the image that is captured for me to save it and view it again to do that I have a input stream that's fired when the capture image is clicked.
using (StreamReader reader = new StreamReader(Request.InputStream))
{
hexString = Server.UrlEncode(reader.ReadLine());
string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
string imagePath = string.Format("~/Pictures/{0}.png", imageName);
File.WriteAllBytes(Server.MapPath(imagePath), ConvertHexToBytes(hexString));
Session["Byte"] = hexString;
// Session["CapturedImage"] = ResolveUrl(imagePath);
Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(ConvertHexToBytes(hexString));
}
I have a method that converts that hex string to bytes:
private static byte[] ConvertHexToBytes(string hex)
{
// MemoryStream stream = new MemoryStream();
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
I want to Display that image using the bytes, I don't want to save the image in any folder. How do I take those bytes and put them into a image?
I have a slandered image tag Image1.imageUrl =? I tried the base64 version but it doesn't work.
How do I take those bytes and put them into a image?
Note: I am making the assumption as per your question that your question is not about converting hex to bytes.
Imagine you have this in your aspx page:
<asp:Image ID="Image1" runat="server" />
In the code below GetImageBytes returns a byte[]. Then, to serve the image (without saving it to a file), all we need to do is this:
using (MemoryStream ms = new MemoryStream(GetImageBytes()))
{
// Image1 is instance of System.Web.UI.WebControls
this.Image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
}
private byte[] GetImageBytes()
{
return System.IO.File.ReadAllBytes(Server.MapPath("~/Content/someImage.jpg"));
}
Try that out by placing an image in your Content folder to test it out. Now that you know it works, you need to make sure it can work with your ConvertHexToBytes method. If it does not, then clearly something is wrong with ConvertHexToBytes method.

Is there a cross-platform solution to ImageSource to byte[]?

I did researches and fell on this solution: http://forums.xamarin.com/discussion/22682/is-there-a-way-to-turn-an-imagesource-into-a-byte-array
Initial question: http://forums.xamarin.com/discussion/29569/is-there-a-cross-platform-solution-to-imagesource-to-byte#latest
We want to upload an image through a HTTP Post, here's what we tried:
HttpClient httpClient = new HttpClient ();
byte[] TargetImageByte = **TargetImageSource**; //How to convert it to a byte[]?
HttpContent httpContent = new ByteArrayContent (TargetImageByte);
httpClient.PostAsync ("https://api.magikweb.ca/debug/file.php", httpContent);
We also are having a hard time with the libraries we gotta include in the using clauses. It seems like using System.IO; works, but it doesn't give us access to classes like FileInfo or FileStream.
Anybody has any idea how this can be done aside from custom platform-specific converters?
Possibly a Xamarin.Forms.ImageSource function toByte()?
Lemme know if you need more information.
TargetImageSource is a Xamarin.Forms.ImageSource.
ImageSource TargetImageSource = null;
Solution (Sten was right)
The ImageSource has to originate from another type to exist, that previous type can be converted to a byte[]. In this case, I use the Xamarin.Forms.Labs to take a picture and it returns a MediaFile in which a FileStream is accessible through the Source property.
//--Upload image
//Initialization
HttpClient httpClient = new HttpClient ();
MultipartFormDataContent formContent = new MultipartFormDataContent ();
//Convert the Stream into byte[]
byte[] TargetImageByte = ReadFully(mediaFile.Source);
HttpContent httpContent = new ByteArrayContent (TargetImageByte);
formContent.Add (httpContent, "image", "image.jpg");
//Send it!
await httpClient.PostAsync ("https://api.magikweb.ca/xxx.php", formContent);
App.RootPage.NavigateTo (new ClaimHistoryPage());
The function:
public static byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream()){
input.CopyTo(ms);
return ms.ToArray();
}
}
I think you're looking at it a bit backwards.
ImageSource is a way to provide a source image for Xamarin.Forms.Image to show some content. If you're already showing something on the screen your Image view was populated with data that came from elsewhere, such as a file or resource or stored in an array in memory... or however else you got that in the first place. Instead of trying to get that data back from ImageSource you can keep a reference to it and upload it as needed.
Maybe you can elaborate a bit on your particular need if you don't feel this solution applies to your case.
Pseudo code:
ShowImage(){
ImageSource imageSource = ImageSource.FromFile("image.png"); // read an image file
xf_Image.Source = imageSource; // show it in your UI
}
UploadImage(){
byte[] data = File.ReadAll("image.png");
// rather than
// byte[] data = SomeMagicalMethod(xf_Image.Source);
HttpClient.Post(url, data);
}
UPDATE:
Since you're taking a picture you can copy the MediaFile.Source stream into a memory stream, then you can reset the memory stream's position to point at the beginning of the stream so that you can read it once again and copy it to the http body.
Alternatively you can store the MediaFile.Source to a file and use ImageSource.FromFile to load it in the UI, and when necessary - you can copy the file's contents into an http post body.

decode Base64 byte Array to Image in C#

I am making a small application in android that browse image from the gallery or take a picture from the camera. Then the selected image is compressed and uploaded to the server. I had compressed the image using Base64 String in android and for uploading image i am making a web service in ASP.NET. But i'm not sure how to decode the string(converted using Base64 in android) into image(the web service should be able to convert it). Please help me.
Thanks in advance
You can convert base64string to image by Image.FromStream. You will need to convert the base64string to stream first.
byte[] imageBytes = Convert.FromBase64String(imgBase64String);
Image img = null;
using (MemoryStream ms1 = new MemoryStream(imageBytes))
{
img = Image.FromStream(ms1);
}
if (img != null)
{
// ...
}

Adding text to a JPG image in ASP.net C# and save to file on server

I'm using the following code (credit to Dolph Larson) to take a pre-made image file in bitmap format on an ASP.net server, draw a string on it and save it to file on the server. In the original code, he dumps the bitmap to the OutputStream, but I'd like to dump it instead to a file.
The version of code below successfully creates the new file, but when I open it, the string does not appear drawn on the image in the new file. I imagine I am missing a step -- when I use bitMapImage.Save("bitmaptest.jpg", ImageFormat.Jpeg) am I just re-saving the original instead of the modified version?
Here is the code:
//Load the Image to be written on.
Bitmap bitMapImage = new
System.Drawing.Bitmap(Server.MapPath("generic.jpg"));
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
graphicImage.DrawString("testing 1 2 3",
new Font("Arial", 20, FontStyle.Bold),
SystemBrushes.WindowText, new Point(0, 0));
Response.ContentType = "image/jpeg";
bitMapImage.Save("bitmaptest.jpg", ImageFormat.Jpeg);
graphicImage.Dispose();
bitMapImage.Dispose();
Thanks in advance!
Your code works just fine; You simply need to specify the path where you want to save the image:
Example:
//Load the Image to be written on.
Bitmap bitMapImage = new
System.Drawing.Bitmap((#"c:\\foo\\generic.jpg"));
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.DrawString("testing 1 2 3",
new Font("Arial", 20, FontStyle.Bold),
SystemBrushes.WindowText, new Point(0, 0));
bitMapImage.Save("c:\\foo\\bitmaptest.jpg", ImageFormat.Jpeg);
graphicImage.Dispose();
bitMapImage.Dispose();
Note In your case, bitMapImage.Save needs to be as follows: bitMapImage.Save(Server.MapPath("~/Images")+"newImage.jpg",ImageFormat.Jpeg); since you are attempting to save the image on an asp.net app. ~/Images in my example is just the virtual directory Images inside your app.
Yes ..You are saving the same image .You have to create a ne wbitmap and save it:-
Bitmap bitMapNew = Bitmap.FromHbitmap(graphicImage.GetHdc());
bitMapNew.Save("bitmaptest.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
Add these lines instead of your bitMapImage.save

FileReference and HttpService Browse Image Modify it then Upload it

I am trying to do an image uploader, user can:
- browse local file with button.browse
- select one and save it as a FileReference.
- then we do FileReference.load() then bind the data to our image control.
- after we make a rotation on it and change the data of image.
- and to finish we upload it to a server.
To change the data of image i get the matrix of the displayed image and transform it then i re-use the new matrix and bind it to my old image:
private function TurnImage():void
{
//Turn it
var m:Matrix = _img.transform.matrix;
rotateImage(m);
_img.transform.matrix = m;
}
Now the mater is that i really don't know how to send the data as a file to my server cause its not stored in the FileReference and data inside FileReference is readOnly so we can't change it or create a new, so i can't use .upload();.
Then i tried HttpService.send but i can't figure out how you send a file and not a mxml.
You can use URLLoader to send Binary ByteArray to server, like:
var urlRequest : URLRequest = new URLRequest();
urlRequest.url = 'path to your server';
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = UploadPostHelper.getPostData( 'image.jpg', byteArray );
urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
// create the image loader & send the image to the server:<br />
var urlLoader : URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.load( urlRequest );
First get bitmapdata for the image:
// set up a new bitmapdata object that matches the dimensions of the captureContainer;
var bmd : BitmapData = new BitmapData( captureContainer.width, captureContainer.height, true, 0xFFFFFFFF );
// draw the bitmapData from the captureContainer to the bitmapData object:<br />
bmd.draw( captureContainer, new Matrix(), null, null, null, true );
Then get byteArray:
var byteArray : ByteArray = new JPGEncoder( 90 ).encode( bmd );
and use the above URLLoader code to send image to server.
It will work fine, except you wouldn't get the file upload progress like the one you get from FileReference.upload. If you can make upload progress work using URLLoader, please post your answer here.

Resources