how seve the grid background after choose image by choose image task
EX:
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
ImageBrush img = new ImageBrush();
img.ImageSource = bmp;
LayoutRoot.Background = img;
//Save grid Background
}
}
help me please
thank you :)
Note: 'Save' means that when the application open next time
be 'grid backgrund' the same background chosen
Try this.. In the example i have used a button to activate the PhotoChooserTask. The XAML is like this.
XAML
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Name="btnSet" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Content="Set Image" Click="btnSet_Click" />
</Grid>
</Grid>
Click event for the button.
C#
private void btnSet_Click(object sender, RoutedEventArgs e)
{
PhotoChooserTask photoTask = new PhotoChooserTask();
photoTask.Completed += photoTask_Completed;
photoTask.PixelHeight = 1280;
photoTask.PixelWidth = 768;
photoTask.Show();
}
In the photoTask_Completed event handler you can save the image to the IsolatedStorage
void photoTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoStore.FileExists(fileName))
{
isoStore.DeleteFile(fileName);
}
using (IsolatedStorageFileStream targetStream = isoStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
{
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = e.ChosenPhoto.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
}
}
Then in the OnNavigatedTo event you can load the image from IsolatedStorage and set it as the background.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
byte[] data;
using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoStore.FileExists(fileName))
{
using(IsolatedStorageFileStream stream = isoStore.OpenFile(fileName, FileMode.Open, FileAccess.Read))
{
data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
}
MemoryStream ms = new MemoryStream(data);
bmp = new BitmapImage();
bmp.SetSource(ms);
ImageBrush img = new ImageBrush();
img.ImageSource = bmp;
LayoutRoot.Background = img;
}
}
}
The variable fileName holds the name of the image saved to the IsolatedStorage. The image is overwritten every time you select a new image from the library. Hope this helps.
try this:
XAML
<Grid x:Name="LayoutRoot">
<Grid.Background>
<ImageBrush x:Name="imgsrc"></ImageBrush>
</Grid.Background>
</Grid>
CS:
if (e.TaskResult == TaskResult.OK)
{
BitmapImage Bitmap = new BitmapImage();
Bitmap.SetSource(e.ChosenPhoto);
imgsrc.ImageSource = Bitmap;
}
for Saving image you would be needed to use isolatedstorage. You would be needed to save your image in Isolatedstorage and have a isolatedsettings variabe for saving the state of the image whether you have choosen any image or not.
If yes then get image from there otherwise no action would be needed, here is a good example from you can have reference for saving and Retriving image from Isolatedstorage Isolated Storage - Read and Save Images
Related
There are around 30-40 images that gets downloaded from the server and saved to local and then file path is passed through which image source is generated. Download call is made whenever user scrolls the collectionview. Sometimes images are getting loaded completely and sometime partially.
<CollectionView
HorizontalOptions="FillAndExpand"
HorizontalScrollBarVisibility="Never"
VerticalScrollBarVisibility="Never"
SelectionMode="Single"
ItemSizingStrategy="MeasureAllItems"
ItemsSource="{Binding Items}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Image}"></Image>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
C#
await Utility.FileHanler.Download(Id, resourceTypeId, material, ThumbURL, token, (arg) =>
{
LoadImage(arg);
});
public async Task Download(int id, int resourceType,string fileName,string thumbnailUrl, CancellationToken token , Action<string> CompletionHandler)
{
string destinationFolder;
destinationFolder = Path.Combine(FileHandler.Images, id.ToString());
try
{
if (!Directory.Exists(destinationFolder))
{
Directory.CreateDirectory(destinationFolder);
}
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
token.ThrowIfCancellationRequested();
WebRequest wr = WebRequest.Create(thumbnailUrl + App.Token);
WebResponse ws = await wr.GetResponseAsync();
Stream s = ws.GetResponseStream();
byte[] buffer = new byte[10240];
var filePath = Path.Combine(destinationFolder, fileName);
var dlStream = new FileStream(filePath, FileMode.Create);
int readBytes = s.Read(buffer, 0, 10240);
while (readBytes > 0)
{
dlStream.Write(buffer, 0, readBytes);
readBytes = s.Read(buffer, 0, 10240);
}
dlStream.Close();
dlStream.Dispose();
s.Close();
s.Dispose();
ws.Close();
CompletionHandler?.Invoke(filePath);
}
catch (Exception ex)
{
throw ex;
}
public void LoadImage(string filePath)
{
Device.BeginInvokeOnMainThread(() =>
{
Image = ImageSource.FromFile(filePath);
});
}
I created an entry where you type in a value, but now I want to create a bitmap with the text of an entry. When I got the bitmap, I can load it in SkiaSharp and use BitmapModifiers on it.
Is this possible?
I would recommend you to go through these examples on github.
Dummy sample could look like this:
This is xaml page:
<StackLayout>
<Entry x:Name="InputText" />
<Button Text="Create Bitmap" Clicked="Button_Clicked" />
</StackLayout>
Codebehind:
SKBitmap helloBitmap;
void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
{
SKImageInfo info = args.Info;
SKSurface surface = args.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear(SKColors.Aqua);
canvas.DrawBitmap(helloBitmap, 0, 0);
}
private void Button_Clicked(object sender, EventArgs e)
{
CreateBitmapFromText(InputText.Text);
}
private void CreateBitmapFromText(string text)
{
// Create bitmap and draw on it
using (SKPaint textPaint = new SKPaint { TextSize = 48 })
{
SKRect bounds = new SKRect();
textPaint.MeasureText(text, ref bounds);
helloBitmap = new SKBitmap((int)bounds.Right,
(int)bounds.Height);
using (SKCanvas bitmapCanvas = new SKCanvas(helloBitmap))
{
bitmapCanvas.Clear();
bitmapCanvas.DrawText(text, 0, -bounds.Top, textPaint);
}
}
SKCanvasView canvasView = new SKCanvasView();
canvasView.PaintSurface += OnCanvasViewPaintSurface;
Content = canvasView;
}
I'm making an app for android with Xamarin forms where the user would select a photo from their library, add a White border to make it a square, then save it. I'm stuck at the saving part, can't figure it out
I am using the normal Xamarin.Forms.Image control
<Image HorizontalOptions="CenterAndExpand"
VerticalOptions="Center"
BackgroundColor="Transparent"
Grid.Column="0"
Grid.Row="0"
x:Name="imgViewer"/>
this is how I select the photo
async void tbAdd_Activated(object sender, System.EventArgs e)
{
var file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
imgViewer.Source = ImageSource.FromFile(file.FilePath);
imgViewer.BackgroundColor = Color.White;
}
}
But then I have a save button to save that final image with the border to the camera roll but I have no idea how to save it, I've searched everywhere but can't seem to find!
Anyone knows how to do that ?
You will have to specific codes in iOS and android to save the images and Also add required permissions in iOS by adding this key to info.Plist file
<key>NSPhotoLibraryAddUsageDescription</key>
<string>$(PRODUCT_NAME)</string>
Android :
MediaStore.Images.Media.InsertImage(Application.Context.ContentResolver, [YourFileName],
System.IO.Path.GetFileName([YourFileName]), string.Empty);
iOS :
var imageSource = CGImageSource.FromUrl(NSUrl.FromFilename( [YourFileName]));
UIImage.FromImage(imageSource.CreateImage(0, null), 1, imageOrientation)
.SaveToPhotosAlbum((image, error) => { // handle success & error here... });
You can check this link for more info.
You can save the image by the following code:
void save_Activated(object sender, System.EventArgs e)
{
if (file != null)
{
byte[] imageBytes;
var FileImage = new Image();
string base64;
using (var fs = new FileStream(file.FilePath, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
base64 = Convert.ToBase64String(buffer);
}
imageBytes = Convert.FromBase64String(base64);
File.WriteAllBytes(filename, imageBytes);
}
So the full code is like this:
string documentsFolder;
string filename;
FileData file;
ImageSource imageSource;
public MainPage()
{
InitializeComponent();
documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
filename = Path.Combine(documentsFolder, "myfile.jpg");
}
async void tbAdd_Activated(object sender, System.EventArgs e)
{
file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
imgViewer.Source = ImageSource.FromFile(file.FilePath);
imgViewer.BackgroundColor = Color.White;
imageSource = imgViewer.Source;
}
}
void save_Activated(object sender, System.EventArgs e)
{
if (file != null)
{
byte[] imageBytes;
var FileImage = new Image();
string base64;
using (var fs = new FileStream(file.FilePath, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
base64 = Convert.ToBase64String(buffer);
}
imageBytes = Convert.FromBase64String(base64);
File.WriteAllBytes(filename, imageBytes);
}
}
And the xamal is:
<Button Text="AddImage" Clicked="tbAdd_Activated">
</Button>
<Button Text="SaveImage" Clicked="save_Activated">
</Button>
<Image HorizontalOptions="CenterAndExpand"
VerticalOptions="Center"
BackgroundColor="Transparent"
Grid.Column="0"
Grid.Row="0"
x:Name="imgViewer"/>
Can i bind image to xaml without needing to use image source (the predominant method) which it is (In xaml page):
<Image Height="170" Width="220" Source="{Binding Source=Img}" ></Image>
because i have image converted from byte array and doesn't have any name or source.
like here:
Image Img = new Image();
Img=ByteArraytoBitmap(ob0[0].Img.ToArray());
public BitmapImage ByteArraytoBitmap(Byte[] byteArray)
{
MemoryStream stream = new MemoryStream(byteArray);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
return bitmapImage;
}
You could just add a BitmapImage property on your object (the class of ob0[0]) and then the bitmap image can be directly be binded to the source of the Image (Note that the binding should be Source="{Binding Img}" and not Source="{Binding Source=Img}".
The other solution would for you to create an attached property, something like this should work:
public class MyAttachedProperty
{
public static readonly DependencyProperty ByteArraySourceProperty =
DependencyProperty.RegisterAttached("ByteArraySource", typeof (Byte[]), typeof (MyAttachedProperty), new PropertyMetadata(default(Byte[],byteArraySource)))
private static void byteArraySource(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Image img = d as Image;
if (e.NewValue != null)
{
img.Source = ByteArraytoBitmap((Byte[]) e.NewValue);
}
}
public static BitmapImage ByteArraytoBitmap(Byte[] byteArray)
{
MemoryStream stream = new MemoryStream(byteArray);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
return bitmapImage;
}
public static void SetByteArraySource(UIElement element, Byte[] value)
{
element.SetValue(ByteArraySourceProperty, value);
}
public static Byte[] GetByteArraySource(UIElement element)
{
return (Byte[]) element.GetValue(ByteArraySourceProperty);
}
}
then to do the binding you can just use it like this:
<Image Height="170" Width="220" local:MyAttachedProperty.ByteArraySource="{Binding Img}" ></Image>
I'm trying to insert image in a button through photochoosertask
but on casting btnSelectImage.Content as Image it gives null
can you please help me out
void photoChooserTask_Completed(object sender, Microsoft.Phone.Tasks.PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
Image contentImage = btnSelectImage.Content as Image;
if (contentImage != null)
{
contentImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(e.OriginalFileName));
}
}
}
void photoChooserTask_Completed(object sender, Microsoft.Phone.Tasks.PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.ChosenPhoto);
contentImage.Source = bitmap;
}
}
Try this.
I am not sure what you xaml looks like. You'll have to use it this way
<Button>
<Image x:Name="contentImage" />
</Button>