I am a newbie in Xamarin. I have been trying to set an image to Imagebutton from specific a URL in C# for Xamarin. I googled and was unable to find a sample code or documentation. It would be helpful if any one provide me with a helpful documentation or a little bit of sample code to do this.
Thanks In Advance... :)
To set the ‘default’ image for a button from local images, call SetImage
button1 = UIButton.FromType(UIButtonType.RoundedRect);
button1.SetImage(UIImage.FromFile ("sample.png"), UIControlState.Normal);
To apply from an URL,
button1 = FindViewById(Resource.Id.RoundedRect);
var imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/test.png");
button1.SetImageBitmap(imageBitmap);
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
Related
This is the URL with image-https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/acid.svg
What I have tried
Sample 1-
-I am using SharpVectors package
public void DrawImage()
{
Image svgImage = new Image();
WpfDrawingSettings settings = new WpfDrawingSettings();
settings.IncludeRuntime = false;
settings.TextAsGeometry = true;
FileSvgReader converter = new FileSvgReader(settings);
DrawingGroup drawing = converter.Read(new Uri("https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/acid.svg"));
if (drawing != null)
{
svgImage.Source = new DrawingImage(drawing);
}
}
sample 1 works perfectly but it's latency is very high, So I wanted to improve the performance.
Sample 2 - I tried using bitmap to improve performance below is code, but the issue is I need to download the image or store in folder and use as path as string which works fine but my condition is my URLs are coming form JSON file in .SVG format, they are dynamic and I am not using any .XAMl files for UI.
UI built in code behind programmatically.
Is there any other way I can display SVG image in WPF?
public void DrawImage()
{
Image dynamicImage = new Image();
dynamicImage.Width = 300;
dynamicImage.Height = 200;
stcdock.Children.Add(dynamicImage);
WpfDrawingSettings settings = new WpfDrawingSettings();
settings.IncludeRuntime = true;
settings.TextAsGeometry = false;
string svgTestFile = #"\Downloads\acid.svg";
StreamSvgConverter converter = new StreamSvgConverter(settings);
MemoryStream memStream = new MemoryStream();
if (converter.Convert(svgTestFile, memStream))
{
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = memStream;
bitmap.EndInit();
dynamicImage.Source = bitmap;
}
}
.svg are not nativly supported in wpf.
https://www.nuget.org/packages/svg
This package promisses to add this functionality.
How can I add the url to the screenshot with c# in Selenium. Is there a good solution for this?
I tried the solution. it works and get the url displayed.
Use the steps below to add a URL to a screenshot in Selenium with C#
1- Create a extension:
public static Screenshot AddURLToImage(this Screenshot screenshot, string url)
{
string base64 = String.Empty;
using (var ms = new MemoryStream(screenshot.AsByteArray, 0, screenshot.AsByteArray.Length))
{
Image image = Image.FromStream(ms, true);
Graphics graphics = Graphics.FromImage(image);
using (var font = new Font("Arial", 11))
{
graphics.DrawString(url, font, Brushes.White, 10, 10);
var imageConverter = new ImageConverter();
byte[] buffer = (byte[])imageConverter.ConvertTo(image, typeof(byte[]));
base64 = Convert.ToBase64String(buffer, Base64FormattingOptions.InsertLineBreaks);
}
}
var screenshotWithUrl = new Screenshot(base64);
return screenshotWithUrl;
}
2- Get a screenshot with Selenium
Screenshot screenshot = ((ITakesScreenshot)Driver).GetScreenshot();
3- Add URL to image and save it
screenshot.AddURLToImage(url).SaveAsFile(path);
Hi all I have a byte[] which I save from the Xamarin Essentials Media Picker, I want to display the image on my XAML page so all I have is a blank XAML page with a StackLayout and in my code I do the following:
Stream stream = new MemoryStream(filebyte);
var imageSource = ImageSource.FromStream(() => stream);
Image test = new Image();
test.Source = imageSource;
test.WidthRequest = 50;
test.HeightRequest = 50;
ImageStack.Children.Add(test);
but when the page loads nothing is there. i'm I missing something. I have even tried this on a fresh project using the latest version of Xamarin Forms and Xamarin Essential's
imgByteArray is Byte[], using following code to add image by behind code.
var stream1 = new MemoryStream(imgByteArray);
image.Source = ImageSource.FromStream(() => stream1);
image.WidthRequest = 50;
image.HeightRequest = 50;
imagestack.Children.Add(image);
Update:
Adding one image in Forms, setting Build action as Embedded resource, then converting this image into byte[], using this byte[] for Image to show. I have no problem.
var image = new Xamarin.Forms.Image();
var assembly = this.GetType().GetTypeInfo().Assembly;
byte[] imgByteArray = null;
var s = assembly.GetManifestResourceStream("FormsSample.f19.png");
if (s != null)
{
var length = s.Length;
imgByteArray = new byte[length];
s.Read(imgByteArray, 0, (int)length);
var stream1 = new MemoryStream(imgByteArray);
image.Source = ImageSource.FromStream(() => stream1);
image.WidthRequest = 50;
image.HeightRequest = 50;
imagestack.Children.Add(image);
}
I want to load an image from url to imageview in c# ( android programming ) after search in google i cant find any good result , thank you for helping
i am using xamarin studio
The very first hit I got from Google was a thread on the Xamarin forums discussing this exact issue:
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
var imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/devices.png");
imagen.SetImageBitmap(imageBitmap);
Both approaches work, but is a good practice to do it asynchronously. Here you have some good examples:
Asynchronous Image Loading in Xamarin Android http://javatechig.com/xamarin/asynchronous-image-loading-xamarin-android
xamarin-store-app image helper https://github.com/xamarin/xamarin-store-app/blob/master/XamarinStore.Droid/Helpers/Images.cs
Am using the below class in Xamarin Android:
public class DownloadImageTask : AsyncTask
{
private ImageView bmImage;
private ProgressBar progressBar;
public DownloadImageTask( ImageView bmImage , ProgressBar progressBar)
{
this.bmImage = bmImage;
this.progressBar = progressBar;
}
protected override void OnPostExecute( Object result )
{
base.OnPostExecute(result);
bmImage.SetImageBitmap(( Bitmap ) result);
if (progressBar != null)
progressBar.Visibility = ViewStates.Gone;
}
protected override Object DoInBackground( params Object[] #params )
{
var urldisplay = #params[0].ToString();
Bitmap mIcon11 = null;
try
{
var req = WebRequest.Create(urldisplay);
var response = req.GetResponse();
var stream = response.GetResponseStream();
mIcon11 = BitmapFactory.DecodeStream(stream);
}
catch ( Exception e )
{
}
return mIcon11;
}
}
Execution :
new DownloadImageTask(imgProfile , progressBar).Execute(uri);
I did this to load an Svg from an url into an ImageView using SkiaSharp.
In the .xml
<ImageView
android:contentDescription=""
android:id="#+id/video_recorder_image"
android:layout_width="wrap_content"
android:layout_height="50dp" />
In the activity/fragment.
private ImageView iconImageView;
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
iconImageView = (ImageView)view.FindViewById(Resource.Id.video_recorder_image);
Bitmap image = GetImageBitmapFromUrl(_iconUrl);
}
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
var svgContent = Convert.ToBase64String(imageBytes, 0, imageBytes.Length);
var byteArray = Convert.FromBase64String(svgContent);
using (var stream = new MemoryStream(byteArray))
{
var bitmap = new SKBitmap(500, 500);
var canvas = new SKCanvas(bitmap);
// load the SVG
var svg = new SkiaSharp.Extended.Svg.SKSvg(new SKSize(500, 500));
svg.Load(stream);
// draw the SVG to the bitmap
canvas.DrawPicture(svg.Picture);
var skData = SKImage.FromBitmap(bitmap).Encode(SKEncodedImageFormat.Png, 100);
// Convert image to string and then to Bitmap
var convertedSvgStream = skData.AsStream();
var convertedImageBytes = new byte[(int)convertedSvgStream.Length];
convertedSvgStream.Seek(0, SeekOrigin.Begin);
convertedSvgStream.Read(convertedImageBytes, 0, (int)convertedSvgStream.Length);
imageBitmap = BitmapFactory.DecodeByteArray(convertedImageBytes, 0, convertedImageBytes.Length);
}
}
}
return imageBitmap;
}
When my page loads and I press button1 I can get the image and can see it.
But when I click it second time it doesn't work at all. I debugged it button1_Click(...) and I am sure that imageData != null.
I really can't figure out what's up... Please help me!
private void button1_Click(object button, RoutedEventArgs e)
{
Guid sid = Guid.Parse("087462df-e4b6-484c-879e-cccc37b4c1f4");
EntityQuery<Screenshot> screen = this._myDomainContext.GetScreenshotQuery(sid);
this._myDomainContext.Load(screen).Completed += (sender, args) =>
{
try
{
byte[] imageData = (((LoadOperation<Screenshot>)sender).Entities.FirstOrDefault()).Screen;
if (imageData != null)
{
BitmapImage img = Utilities.Graphics.GetImage(imageData);
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image1.Source = null;
image1.Source = img;
}
}
catch
{
}
};
}
and
public static BitmapImage GetImage(byte[] rawImageBytes)
{
BitmapImage imageSource = null;
try
{
using (MemoryStream stream = new MemoryStream(rawImageBytes))
{
stream.Seek(0, SeekOrigin.Begin);
BitmapImage b = new BitmapImage();
b.SetSource(stream);
imageSource = b;
}
}
catch
{
}
return imageSource;
}
Try changing the overload of Load:
this._myDomainContext.Load(screen, LoadBehavior.RefreshCurrent, true).Completed+= ...
I'm not completely sure on the cause if your issue, but I have a few pointers on the code with regards to using BitmapImage's.
There is no need to set the image1.Source property to null before assigning it with an actual source.
Don't dispose the stream you pass to the BitmapImage in case the control is trying to read from it.
I personally make use of BeginInit(...), StreamSource and EndInit(...) when working with BitmapImage's.