I try to display an image, stored as blob in a table.
So I need to convert a byte[] into a Vaadin Image class (I guess that's the best way to display it ?).
I try this solution (4 years old):
https://vaadin.com/forum/thread/10271496/byte-array-to-vaadin-image
it's not working :
new StreamResource.StreamSource() { -> Cannot resolve symbol 'StreamSource'
How can I do it in Vaadin 13 ?
Here is a solution:
private Image convertToImage(byte[] imageData)
{
StreamResource streamResource = new StreamResource("isr", new InputStreamFactory() {
#Override
public InputStream createInputStream() {
return new ByteArrayInputStream(imageData);
}
});
return new Image(streamResource, "photo");
}
Related
I am using Vaadin 8 and I am facing a problem.
In my constructor, I create a grid which I add to a layout.
Grid<Row> grid = new Grid<>(); grid.removeAllColumns(); //Here, I add columns to the grid grid.addColumn(... grid.addColumn(… …
I then want to add a converter to my grid as follows:
grid.getColumn("delete").setConverter(new StringToUrlConverter("dustbin"));
What I do not understand is the error message indicating why I cannot add the converter. The error message is the folloing one:
The method setConverter(StringToUrlConverter) is undefined for the type >Grid.Column<ContactView.Row,capture#1-of ?>
So how do I have to set my converter?
This is my converter:
package com.example.vaadin;
import com.vaadin.data.Converter;
import com.vaadin.data.Result;
import com.vaadin.data.ValueContext;
public class StringToUrlConverter implements Converter<String, String> {
/**
*
*/
private static final long serialVersionUID = 1L;
String imagePath = "";
public StringToUrlConverter(String path) {
this.imagePath=path;
}
public String getImagePath() {
return imagePath;
}
#Override
public Result<String> convertToModel(String value, ValueContext context) {
return Result.ok(null);
}
#Override
public String convertToPresentation(String value, ValueContext context) {
if(value.equals("delete")) {
return "<span><img src='img/" + getImagePath() + ".jpg' width='20' height='20'></span>";
}
return "";
}
}
There is no setConverter method in Vaadin 8, it was in Vaadin 7. Instead in Vaadin 8 and newer versions you should use version of addColumn method with value provider. See old discussion in Vaadin's Forum.
StringToUrlConverter converter = new StringToUrlConverter (path);
grid.addColumn(row -> converter.convertToPresentation(row.getDelete(), String.class, ui.getLocale())).setCaption("Delete");
But, in your case you probably do not need that either. I see from your code that you simply want to add delete button or something like that in the Grid's cell.
You can add component in Grid from Vaadin 8 onwards using:
grid.addComponentColumn(row -> {
Image image = new Image();
image.setSrc(path);
image.addClickListener(event -> {
// add code to remove the row
grid.getDataProvider().refreshAll();
});
return image;
}
I'm working on Xmarin Forms(PCL) project, I want to convert the StackLayout to Image / buffer and send it to printer for hard print.
Can anyone suggest how to do it in (Xamarin.Android & Xamarin.iOS).
You can't. Xamarin does not have that kind of feature. You should write a Renderer for your UIComponent.
Fortunately there is an Objective-C iOS implementation, and an Android one as well. You can inspire from them.
Taken from this link, which I have personally used, quite a while back though, the following code will take a screenshot of the entire page.
I ended up modifying the code to only take a screenshot of a specific view on the page and also changed a few other things but this example is what I based it off of, so let me know if you would rather see that code and/or if something below is not working for you.
First you create an interface in your Forms project, IScreenshotManager.cs for example:
public interface IScreenshotManager {
Task<byte[]> CaptureAsync();
}
Now we need to implement our interface in Android, ScreenshotManager.cs for example:
public class ScreenshotManager : IScreenshotManager {
public static Activity Activity { get; set; }
public async System.Threading.Tasks.Task<byte[]> CaptureAsync() {
if(Activity == null) {
throw new Exception("You have to set ScreenshotManager.Activity in your Android project");
}
var view = Activity.Window.DecorView;
view.DrawingCacheEnabled = true;
Bitmap bitmap = view.GetDrawingCache(true);
byte[] bitmapData;
using (var stream = new MemoryStream()) {
bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
return bitmapData;
}
}
Then set ScreenshotManager.Activity in MainActivity:
public class MainActivity : Xamarin.Forms.Platform.Android.FormsApplicationActivity {
protected override async void OnCreate(Android.OS.Bundle bundle) {
...
ScreenshotManager.Activity = this; //There are better ways to do this but this is what the example from the link suggests
...
}
}
Finally we implement this on iOS, ScreenshotManager.cs:
public class ScreenshotManager : IScreenshotManager {
public async System.Threading.Tasks.Task<byte[]> CaptureAsync() {
var view = UIApplication.SharedApplication.KeyWindow.RootViewController.View;
UIGraphics.BeginImageContext(view.Frame.Size);
view.DrawViewHierarchy(view.Frame, true);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
using(var imageData = image.AsPNG()) {
var bytes = new byte[imageData.Length];
System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, bytes, 0, Convert.ToInt32(imageData.Length));
return bytes;
}
}
}
I want to display an BufferedImage that is returned by some API ( a Java Library for Canon Hack Development Kit) in my Vaadin Application without saving it to the file system. Is that somehow possible? It doesn't seem to be much of a hassle in swing but I have found no way to do it in Vaadin so far.
Yes, this is perfectly possible with Vaadin using a com.vaadin.server.StreamResource. A StreamResource provides the data of some InputStream and can be used anywhere a com.vaadin.server.Resource is expected (i.e. links, images, icons...).
The following example method creates a StreamResource for a BufferedImage on the fly:
private StreamResource createStreamResource() {
return new StreamResource(new StreamSource() {
#Override
public InputStream getStream() {
String text = "Date: " + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM).format(new Date());
BufferedImage bi = new BufferedImage(370, 30,
BufferedImage.TYPE_3BYTE_BGR);
bi.getGraphics().drawChars(text.toCharArray(), 0,
text.length(), 10, 20);
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bi, "png", bos);
return new ByteArrayInputStream(bos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}, "dateImage.png");
}
This can be used with an com.vaadin.ui.Image as follows:
Image image = new Image("", createStreamResource());
layout.addComponent(image);
Refer to the Vaadin Docs about Stream Resources for more information.
is there any possibility to export charts done with hightcharts in powerpoint?else can someone help me to find a solution?
Thanx
Just export it to an image (PNG or JPG) and add that image to a powerpoint slide? Most highcharts graphs have a download (export) button in the upper right corner of the chart.
I know this is old but I am currently trying to achieve the same thing.
If you are happy to use png or jpg then I would go with phantonJS (OpenQA.Selenium.PhantomJS) to extract an svg and then any conversion mechanism to convert to png/jpg
public IList<string> ExtractSVGs(string htmlFilePath)
{
IList<string> SVGs = new List<string>();
foreach (string chart in getChartIds(htmlFilePath))
{
SVGs.Add(ExtractSVG(htmlFilePath, chart));
}
return SVGs;
}
private IList<string> getChartIds(string htmlFilePath)
{
IList<string> chartIds = new List<string>();
string whatToFind = #" ""renderTo"": """;
foreach (string line in (System.IO.File.ReadLines(htmlFilePath)))
{
if (line.StartsWith(whatToFind))
chartIds.Add("chart" + line.Substring(line.IndexOf(whatToFind) + whatToFind.Length, 32));
}
return chartIds;
}
private string ExtractSVG(string htmlFilePath, string chartId)
{
var driverService = PhantomJSDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
driverService.LoadImages = true;
driverService.ProxyType = "none";
driverService.LocalToRemoteUrlAccess = true;
driverService.WebSecurity = false; // may not be necessary
using (var driver = new PhantomJSDriver(driverService))
{
driver.Navigate().GoToUrl(new Uri("file:///" + htmlFilePath));
string svg = (string)driver.ExecuteScript(String.Format("return {0}.getSVG();", chartId), null);
driver.Close();
return svg;
}
}
You could alter the JS to export directly to png but that would require linking into an export server (or having that code run locally as well).
On a side note you may need to alter the what to find depending on how you build up your html files.
I would like to save the PhotoResult from the cameraCaptureTask into my class which I'm using as a collection and then saving into Isolated Storage:
void cameraCaptureTask_Completed(object sender, PhotoResult e)
This is part of an ObservableCollection. I want to save the photo into this collection.
[DataMember]
public Image VehicleImage
{
get
{
return _vehicleImage;
}
set
{
if (value != _vehicleImage)
{
_vehicleImage = value;
NotifyPropertyChanged("VehicleImage");
}
}
}
I'm using the example from: http://www.blog.ingenuitynow.net and in the example it works fine, but it is setting up an individual Isolated Storage and I would just like to join to my existing collection.
I'm thinking that I can't use the Image type. What would be the best way to accomplish what I'm hoping to do?
Just to answer the comment below. This is what the .Save is doing:
public static void Save<T>(string name, T objectToSave)
{
using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
using (IsolatedStorageFileStream storageFileStream = new IsolatedStorageFileStream(name, System.IO.FileMode.Create, storageFile))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(storageFileStream, objectToSave);
}
}
I think I finally figured out your issue. In your ObservableCollection I personally would not keep an image in there. Instead I would keep a BitmapSource to use less resources, however you may have reasoning why your doing that.
My Process
Convert the Image.Source(BitmapSource) to a byte[]
Save the byte[] to storage
Load the byte[] from storage
Convert the byte[] to and a Image.Source(BitmapSource)
Save Generic To Isolated Storage (In my utility class: IsolatedStorage_Utility.cs)
public static void Save<T>(string fileName, T item)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(fileStream, item);
}
}
}
Load Generic To Isolated Storage (In my utility class: IsolatedStorage_Utility.cs)
public static T Load<T>(string fileName)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(fileStream);
}
}
}
Convert BitmapSource to byte[] (In my utility class: Image_Utility.cs)
public static byte[] ImageToByteArray(BitmapSource bitmapSource)
{
using (MemoryStream stream = new MemoryStream())
{
WriteableBitmap writableBitmap = new WriteableBitmap(bitmapSource);
Extensions.SaveJpeg(writableBitmap, stream, bitmapSource.PixelWidth, bitmapSource.PixelHeight, 0, 100);
return stream.ToArray();
}
}
Convert byte[] to BitmapSource (In my utility class: Image_Utility.cs)
public static BitmapSource ByteArrayToImage(byte[] bytes)
{
BitmapImage bitmapImage = null;
using (MemoryStream stream = new MemoryStream(bytes, 0, bytes.Length))
{
bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
}
return bitmapImage;
}
Example
private void TestImageConversion(object sender, RoutedEventArgs e)
{
byte[] image1AsByteArray = Image_Utility.ImageToByteArray((BitmapSource)Image1.Source);
IsolatedStorage_Utility.Save<byte[]>("Image1.jpg", image1AsByteArray);
BitmapSource image1AsBitmapImage = Image_Utility.ByteArrayToImage(IsolatedStorage_Utility.Load<byte[]>("Image1.jpg"));
Image2.Source = image1AsBitmapImage;
}
Keep in mind this is a jpg saving. If you want to save a png thn you need to use a library of CodePlex or create your own PNGEncoder.
I hope this helps!
Actually in that blog, he knows the ImageFileName stored recently so he is able to retreive the same image from the Isolated storage. i dont think so that example helps you according to your comment.
But If you want store the Picture along with the object means you have to serialize whole object along with the picture taken.
serializing the picture is achieved by converting stream you got to byte[] array and you can convert from byte[] array to BitmapImage again.)
Image conversion and serialization is expalianed here in this link
use this sample and you can serialize with whole object.
In this example I'm excepting that you got ObservableCollection where you want to store all of the images lets say it's name is VehicleImages.
So at the cameraCaptureTask_Completed you load all of the data from IsolatedStorage to VehicleImages and now you add the new VehicleImage to VehicleImages and save it to IsolatedStorage.
Code for save and load:
public static void Save<T>(string name, T objectToSave)
{
using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream storageFileStream = new IsolatedStorageFileStream(name, System.IO.FileMode.Create, storageFile))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(storageFileStream, objectToSave);
}
}
}
public ObservableCollection<T> Read<T>(string name)
{
using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream storageFileStream = new IsolatedStorageFileStream(name, System.IO.FileMode.Open, storageFile))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
return (ObservableCollection<T>)serializer.ReadObject(storageFileStream);
}
}
}