How to resize images in windows phone 8 applications? - image

How to Resize the image in windows phone 8.0 application using C# without loss of quality and to display full image
What I did,
My XAML Code:
<StackPanel Orientation="Vertical">
<TextBlock Text="Select Image" FontSize="45" Height="106"></TextBlock>
<Image Name="ImgPrev" Height="455" Stretch="None" ></Image>
</StackPanel>
My C# code
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
BitmapImage image = new BitmapImage();
image.SetSource(Application.GetResourceStream(new Uri(#"Assets/Bug.jpg", UriKind.Relative)).Stream);
image.DecodePixelType = DecodePixelType.Logical;
image.CreateOptions = BitmapCreateOptions.BackgroundCreation;
image.CreateOptions = BitmapCreateOptions.DelayCreation;
Image img = new Image();
img.Source = image;
WriteableBitmap wb = new WriteableBitmap(image);
wb.Resize(1000, 1000, WriteableBitmapExtensions.Interpolation.Bilinear);
using(MemoryStream stream=new MemoryStream())
{
wb.SaveJpeg(stream, 1000, 1000, 0, 100);
BitmapImage resize = new BitmapImage();
resize.SetSource(stream);
ImgPrev.Source = resize;
}
}
The original image
Actual size of the image is 38 MB, Dimention 10240x6400 , height:10240, width:6400
What result I am getting is below image

Related

How to merge two image in Xamarin Forms?

I'm developing a Xamarin Forms iOS app. In the xaml file, there is a grid.
<Grid x:Name="QrCodeSite" HeightRequest="300" Margin="37, 37, 37, 0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
</Grid>
In the related .cs file, I use ZXing.Net.Mobile.Forms to generate a QR code and place it in the grid. And I put my logo in the same grid, which will finally appear at the center of the QR code.
var barcode = new ZXingBarcodeImageView
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
barcode.BarcodeFormat = ZXing.BarcodeFormat.QR_CODE;
barcode.BarcodeOptions.Width = 650;
barcode.BarcodeOptions.Height = 650;
barcode.BarcodeOptions.Margin = 1;
barcode.BarcodeValue = value;
var img = new Image
{
Source = "logo.png",
WidthRequest = 70,
HeightRequest = 70,
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
QrCodeSite.Children.Clear();
QrCodeSite.Children.Add(barcode);
QrCodeSite.Children.Add(img);
The problem is, maybe my phone (iPhone 6s plus) is too slow, sometimes the logo appears first and after a lag (around 1 second) the QR code is shown. How can I merge the QR code and the logo into one image and then add it to the grid?
You can using SkiaSharp to display Image or merge images . Having a look at how to Display SkiaSharp bitmaps to download sample project to research at it.
Based on Drawing on existing bitmaps reference , you can modify it as follow :
public partial class MonkeyMoustachePage : ContentPage
{
SKBitmap monkeyBitmap;
public MonkeyMoustachePage()
{
Title = "Monkey Moustache";
monkeyBitmap = BitmapExtensions.LoadBitmapResource(GetType(),
"SkiaSharpFormsDemos.Media.MonkeyFace.png");
SKBitmap iconImage = BitmapExtensions.LoadBitmapResource(GetType(),
"SkiaSharpFormsDemos.Media.GooglePlaylogo.png");
int offset = monkeyBitmap.Width / 2 - iconImage.Width / 2;
int offsetTop = monkeyBitmap.Height / 2 - iconImage.Height / 2;
// Create canvas based on bitmap
using (SKCanvas canvas = new SKCanvas(monkeyBitmap))
{
canvas.DrawBitmap(iconImage, SKRect.Create(offset, offsetTop, iconImage.Width, iconImage.Height));
}
// Create SKCanvasView to view result
SKCanvasView canvasView = new SKCanvasView();
canvasView.PaintSurface += OnCanvasViewPaintSurface;
Content = canvasView;
//save the new image
using (MemoryStream memStream = new MemoryStream())
using (SKManagedWStream wstream = new SKManagedWStream(memStream))
{
monkeyBitmap.Encode(wstream, imageFormat, quality);
byte[] data = memStream.ToArray();
// Check the data array for content!
bool success = await DependencyService.Get<IPhotoLibrary>().SavePhotoAsync(data, folder, filename);
// Check return value for success!
}
}
void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
{
SKImageInfo info = args.Info;
SKSurface surface = args.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear();
canvas.DrawBitmap(monkeyBitmap, info.Rect, BitmapStretch.Uniform);
}
}
Then you will see a logo icon will display in original image :
If you want to save SkiaSharp bitmaps to files , have a look at this :https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/bitmaps/saving#exploring-the-image-formats
Note: BitmapExtensions.cs file is from sample project .By the way , when adding image to project , you need to set Build ACtion of image be Embedded resource .As follow :

Xamarin Forms Resize Image inside Listview

How can I set the size of the image inside of a list view. Currently I have several lists that have icons but I don't see any options for changing the aspect ratio or size of the image so it just gets blown up to the height of the list item.
all the images are from the Drawable folder
var cell = new DataTemplate(typeof(MenuTextCell));
cell.SetBinding(TextCell.TextProperty, "Title");
cell.SetBinding(ImageCell.ImageSourceProperty, "IconSource");
cell.SetValue(BackgroundColorProperty, Color.Transparent);
cell.SetValue(TextCell.TextColorProperty, Color.FromHex("262626"));
I am using a custom renderer
public class MenuTextCellRenderer : ImageCellRenderer
{
protected override View GetCellCore (Cell item, View convertView, ViewGroup parent, Context context)
{
var cell = (LinearLayout)base.GetCellCore (item, convertView, parent, context);
cell.SetPadding(20, 10, 0, 10);
cell.DividerPadding = 50;
var div = new ShapeDrawable();
div.SetIntrinsicHeight(1);
div.Paint.Set(new Paint { Color = Color.FromHex("b7b7b7").ToAndroid() });
if (parent is ListView)
{
((ListView)parent).Divider = div;
((ListView)parent).DividerHeight = 1;
}
var icon = (ImageView)cell.GetChildAt(0);
var label = (TextView)((LinearLayout)cell.GetChildAt(1)).GetChildAt(0);
label.SetTextColor(Color.FromHex("262626").ToAndroid());
label.TextSize = Font.SystemFontOfSize(NamedSize.Large).ToScaledPixel();
label.TextAlignment = TextAlignment.Center;
label.Text = label.Text.ToUpper();
var secondaryLabel = (TextView)((LinearLayout)cell.GetChildAt(1)).GetChildAt(1);
secondaryLabel.SetTextColor(Color.FromHex("262626").ToAndroid());
secondaryLabel.TextSize = Font.SystemFontOfSize(NamedSize.Large).ToScaledPixel();
label.TextAlignment = TextAlignment.Center;
return cell;
}
You are now dealing with an Android ImageView.
You have your reference via var icon = (ImageView)cell.GetChildAt(0).
You can now customize it via methods such as .setScaleType() for aspect ratio related, and use .layout() to change the position / size.
Try something like this on your ListView.ItemTemplate, instead of using the imagecell. You can also write your custom cell.
<DataTemplate>
<ViewCell>
<StackLayout VerticalOptions="FillAndExpand" Orientation="Horizontal" Padding="10">
<Image Aspect="AspectFill" HeightRequest ="20" WidthRequest="20" Source="{Binding IconSource}" />
<Label Text="{Binding Title}" YAlign="Center" Font="Medium" />
</StackLayout>
</ViewCell>

Crop Image in Canvas or scrollview?

I have put an image in the scrollview and canvas as xaml below:
<ScrollViewer x:Name="scroll" HorizontalAlignment="Center" VerticalAlignment="Center" Width="340" Height="480">
<Canvas x:Name="canvas" HorizontalAlignment="Center" VerticalAlignment="Center" Width="340" Height="480" Background="Blue">
<Image x:Name="photo" Stretch="Fill" HorizontalAlignment="Center" VerticalAlignment="Center" ManipulationMode="All" Width="340" Height="480">
<Image.RenderTransform>
<CompositeTransform/>
</Image.RenderTransform>
</Image>
</Canvas>
</ScrollViewer>
After that, I created a button to load and crop the image:
private async void btnCrop_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker fileOpenPicker = new FileOpenPicker();
fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
fileOpenPicker.FileTypeFilter.Add(".jpg");
fileOpenPicker.FileTypeFilter.Add(".jpeg");
fileOpenPicker.FileTypeFilter.Add(".png");
fileOpenPicker.FileTypeFilter.Add(".bmp");
file = await fileOpenPicker.PickSingleFileAsync();
if (file != null)
{
var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
BitmapTransform transform = new BitmapTransform();
BitmapBounds bounds = new BitmapBounds();
bounds.X = bounds.Y = 0;
bounds.Height = bounds.Width = 150;
transform.Bounds = bounds;
PixelDataProvider pix = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);
byte[] pixels = pix.DetachPixelData();
WriteableBitmap cropBmp = new WriteableBitmap(340, 480);
Stream pixStream = cropBmp.PixelBuffer.AsStream();
pixStream.Write(pixels, 0, 150 * 150 * 4);
photo.Source = cropBmp;
}
}
The image has been crop and displayed successful. But when I zoom my image, I just want crop the image within the canvas instead of hard code. The code above is hard code the BitmapBounds width and height. How do I solve it? Thanks

how to move the image control to specific x y co ordination by using of animation class in windows phone 7

Please help me how to move the image as automatically to specific x y position by using of animation class in windows phone 7, i have tried by Point animation class but this is not working for image control but working for object, so please tell me what kind of animation class should i use for moving image in windows phone 7
and my code is
XAML
</PointAnimation>
</Storyboard>
</Canvas.Resources>
<Image Source="qq.jpg" Width="200" Height="100" x:Name="MyImage" Canvas.Left="10" Canvas.Top="10" />
</Canvas>
</Grid>
c#
private void canvas1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Point mypoint = new Point();
mypoint.X = 10;
mypoint.Y = 200;
MyPointAnimation.To = mypoint;
myStoryboard.Begin();
}
you can do something like that :
<Image x:Name="myImage"
Canvas.Left="10"
Canvas.Top="10"
Width="200"
Height="100"
Source="/Assets/qq.jpg">
<Image.RenderTransform>
<TranslateTransform />
</Image.RenderTransform>
</Image>
and then in code behind :
TranslateTransform trans = myImage.RenderTransform as TranslateTransform;
DoubleAnimation anima1 = new DoubleAnimation();
anima1.To = 150;
Storyboard.SetTarget(anima1, trans);
Storyboard.SetTargetProperty(anima1, new
PropertyPath(TranslateTransform.XProperty));
// Create storyboard, add animation, and fire it up!
Storyboard storyboard = new Storyboard();
storyboard.Children.Add(anima1);
storyboard.Begin();

Programmatically add Pivot Items

I want to display a list of photos in a Pivot Control, so I have this xaml
<Grid x:Name="LayoutRoot" Background="Transparent">
<controls:Pivot x:Name="DiaporamaPivot">
</controls:Pivot>
</Grid>
and in the code behind I do :
public Diaporama()
{
InitializeComponent();
PivotItem p = new PivotItem();
Image i = new Image();
i.Source = new BitmapImage(new Uri("/image.jpg", UriKind.Relative));
p.Margin = new Thickness(0, -10, 0, -2);
DiaporamaPivot.Items.Add(i);
}
Any idea why I get an exception
You are adding i (Image) to Pivot. Instead, add i to p and then, add p (PivotItem) to Pivot.
public Diaporama()
{
InitializeComponent();
PivotItem p = new PivotItem();
Image i = new Image();
i.Source = new BitmapImage(new Uri("/image.jpg", UriKind.Relative));
p.Margin = new Thickness(0, -10, 0, -2);
p.Content = i;
DiaporamaPivot.Items.Add(p);
}

Resources