Convert image from sitecore field to base64 string - image

I need some help with an issue if anyone could help me. I am trying get an image from a Sitecore field and convert it afterwards to a base64 string.
What i have done is getting that content into an ImageField datatype, but i can't seem to find a solution to convert it to base64.
Sitecore.Data.Fields.ImageField img = itm.Fields["image"];
Is anyone able to help me?
Best regards,
Ionut.

You need to get the media item linked from the image field and create the base64 string from the media item file stream:
ImageField imageField = itm.Fields["Image"];
MediaItem mediaItem = imageField.MediaItem;
Stream stream = mediaItem.GetMediaStream();
Byte[] bytes = new Byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
img64.Src = "data:" + mediaItem.MimeType + ";base64," + Convert.ToBase64String(bytes);

Related

Convert Base64 String to Image file in Groovy

i checked with old threads but didn't find anything helpful.
i am a JD Edwards developer and we have a requirement in jde Orchestrator to process base64 string.
Can anyone help me and share full code for this?
i am new in groovy script.
def base64str = 'R0lGODlhAwADAHAAACwAAAAAAwADAIHsHCT97KYAAAAAAAACBIQRBwUAOw==' // < base64 string with 3x3 gif inside
def filename = System.properties['user.home']+'/documents/my.gif' // < filename with path
// save decoded base64 bytes into file
new File(filename).bytes = base64str.decodeBase64()
as a result you there should be a new file my.gif in current user/ documents folder
with 3x3 pixels image (43 bytes file)

Google CloudML serving_input_receiver_fn() b64 decode error

I am sending a base64 encoded image via AJAX POST to a model stored in Google CloudML. I am getting an error telling me that my input_fn(): is failing to decode the image and transform it into jpeg.
Error:
Prediction failed: Error during model execution:
AbortionError(code=StatusCode.INVALID_ARGUMENT,
details="Expected image (JPEG, PNG, or GIF), got
unknown format starting with 'u\253Z\212f\240{\370
\351z\006\332\261\356\270\377' [[{{node map/while
/DecodeJpeg}} = DecodeJpeg[_output_shapes=
[[?,?,3]], acceptable_fraction=1, channels=3,
dct_method="", fancy_upscaling=true, ratio=1,
try_recover_truncated=false,
_device="/job:localhost/replica:0 /task:0
/device:CPU:0"](map/while/TensorArrayReadV3)]]")
Below is the full Serving_input_receiver_fn():
The first step I believe is to handle the incoming b64 encoded string and decode it. This is done with:
image = tensorflow.io.decode_base64(image_str_tensor)
The next step I believe is to open the bytes, but this is where I dont know how to handle the decoded b64 string with tensorflow code and need help.
With a python Flask app this can be done with:
image = Image.open(io.BytesIO(decoded))
pass the bytes through to get decoded by tf.image.decode_jpeg ????
image = tensorflow.image.decode_jpeg(image_str_tensor, channels=CHANNELS)
Full input_fn(): code
def serving_input_receiver_fn():
def prepare_image(image_str_tensor):
image = tensorflow.io.decode_base64(image_str_tensor)
image = tensorflow.image.decode_jpeg(image_str_tensor, channels=CHANNELS)
image = tensorflow.expand_dims(image, 0) image = tensorflow.image.resize_bilinear(image, [HEIGHT, WIDTH], align_corners=False)
image = tensorflow.squeeze(image, axis=[0])
image = tensorflow.cast(image, dtype=tensorflow.uint8)
return image
How do I decode my b64 string back into jpeg and then convert the jpeg to a tensor?
This is a sample for processing b64 images.
HEIGHT = 224
WIDTH = 224
CHANNELS = 3
IMAGE_SHAPE = (HEIGHT, WIDTH)
version = 'v1'
def serving_input_receiver_fn():
def prepare_image(image_str_tensor):
image = tf.image.decode_jpeg(image_str_tensor, channels=CHANNELS)
return image_preprocessing(image)
input_ph = tf.placeholder(tf.string, shape=[None])
images_tensor = tf.map_fn(
prepare_image, input_ph, back_prop=False, dtype=tf.uint8)
images_tensor = tf.image.convert_image_dtype(images_tensor, dtype=tf.float32)
return tf.estimator.export.ServingInputReceiver(
{'input': images_tensor},
{'image_bytes': input_ph})
export_path = os.path.join('/tmp/models/json_b64', version)
if os.path.exists(export_path): # clean up old exports with this version
shutil.rmtree(export_path)
estimator.export_savedmodel(
export_path,
serving_input_receiver_fn=serving_input_receiver_fn)

How to convert Embedded image to Base64 string in xamarin forms..?

I want to convert an Embedded image to base 64 string. The image is in PCL solution so let me know how to convert an image into base64. As I tried lots of ways but I am not getting the file path properly. So please help me with this.
//file to base64 string
byte[] b = System.IO.File.ReadAllBytes(FileName);
String s = Convert.ToBase64String(b);
//base64 string to file
byte[] data = Convert.FromBase64String(s);
System.IO.File.WriteAllBytes(FileName2, data);
Since it is an embedded resource getting the path for the image is a problem to convert it into a stream, you can take the following steps to get the path of your embedded image:
string imagePath = "NameOfProject.Assets.applicationIcon.png";
Note: This is the sample path in your case you will give your path, Where the name of the project is the name of the project, Assets is the folder in which I have the image and application icon is the image. (I hope you understood what I am doing here)
After that get the Assembly details something like this:
Assembly assembly = typeof(NameOfClass).GetTypeInfo().Assembly;
Then inside a using statement convert your image into a stream, Something like this
string result;
using (Stream stream = assembly.GetManifestResourceStream(imagePath))
{
long length = stream.Length;
byte[] buffer = new byte[length];
stream.Read(buffer, 0, (int)length);
result = Convert.ToBase64String(data);
}
Revert in case of queries.

how to create a photo unique filename for isolated storage

I'm adding a Astronomy Picture of The Day to my Windows Phone Astronomy app, and I want to allow users to save the displayed photo to their media library. All of the examples I found show how to do this, but all of the filenames are hard coded and overwrite files that have the existing name. So I need a way to create a unique file name. How can I adjust this example to create a unique filename?
// Create a filename for JPEG file in isolated storage.
String tempJPEG = "fl.jpg";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists(tempJPEG))
{
store.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = store.CreateFile(tempJPEG);
StreamResourceInfo sri = null;
Uri uri = new Uri("fl.jpg", UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
Thanks in advance for any help.
Provided you don't expect multiple saves per second
String tempJPEG = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")+".jpg";
Or some variant of that.
Just one way.

Parse PDF with ABCPDF

I want to parse a PDF document I download with ABCPDF, but I cant find any elements in the document or how to reach them and iterate them. I want to parse out some text.
var webClient = new WebClient();
var bytes = webClient.DownloadData("http://test.com/test.pdf");
var doc = new Doc();
doc.Read(bytes);
Use the Doc.GetText method to extract content from the current page, specifying the format in which content is to be returned.
doc.PageNumber = 1;
string pageContent = doc.GetText("Text");
The example above will return plain text in layout order. Specifying "SVG" or "SVG+" returns additional information along with the text, such as style and position.

Resources