I have a Windows Phone 8 Application where I am taking a picture. I would like to get the Base64 String from the e.ChosenPhoto object but not sure how to go about it.
Code:
private void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
var bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
imgPhoto.Source = bmp;
imgPhoto.Stretch = Stretch.Uniform;
// Get the base64 String from the e.ChosenPhoto or the bmp object
}
}
The following is how I solved the issue:
byte[] bytearray = null;
using (var ms = new MemoryStream())
{
if (imgPhoto.Source != null)
{
var wbitmp = new WriteableBitmap((BitmapImage) imgPhoto.Source);
wbitmp.SaveJpeg(ms, 46, 38, 0, 100);
bytearray = ms.ToArray();
}
}
if (bytearray != null)
{
Sighting.Instance.ImageData = Convert.ToBase64String(bytearray);
PhotoModel.Instance.BitmapImage = bitmapImage;
}
Related
I used
private BitmapImage byteArrayToImage(byte[] byteArrayIn)
{
try
{
MemoryStream stream = new MemoryStream();
stream.Write(byteArrayIn, 0, byteArrayIn.Length);
stream.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
BitmapImage returnImage = new BitmapImage();
returnImage.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
returnImage.StreamSource = ms;
returnImage.EndInit();
return returnImage;
}
catch (Exception ex)
{
throw ex;
}
return null;
}
This method in my application to convert byte array to an image. But it throws "Parameter is not valid" exception.. why it is happening..? Is there any alternative method.??
Hi this should be working:
private static BitmapImage LoadImage(byte[] imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
return image;
}
If you have array like this:
byte[] byteArrayIn = new byte[] {255, 128, 0, 200};
And you want something like:
Use:
BitmapSource bitmapSource = BitmapSource.Create(2, 2, 300, 300,PixelFormats.Indexed8, BitmapPalettes.Gray256, byteArrayIn, 2);
Image.Source = bitmapSource;
In xaml:
<Image RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased" x:Name="Image"></Image>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
var of = new OpenFileDialog();
of.Filter = "Image files (*.png;*.jpeg)|*.png;*.jpeg|All files (*.*)|*.*";
var res = of.ShowDialog();
if (res.HasValue)
{
imgPreview.Source = new BitmapImage(new Uri(of.FileName));
var t = Utils.ConvertBitmapSourceToByteArray(imgPreview.Source as BitmapSource);
var d = Utils.ConvertBitmapSourceToByteArray(new BitmapImage(new Uri(of.FileName)));
var s = Utils.ConvertBitmapSourceToByteArray(imgPreview.Source);
var enc = Utils.ConvertBitmapSourceToByteArray(new PngBitmapEncoder(), imgPreview.Source);
//imgPreview2.Source = Utils.ConvertByteArrayToBitmapImage(enc);
imgPreview2.Source = Utils.ConvertByteArrayToBitmapImage2(enc);
//var i = 0;
}
else
{
MessageBox.Show("Select a currect file...");
}
}
}
/util.cs/
public class Utils
{
public static byte[] ConvertBitmapSourceToByteArray(BitmapEncoder encoder, ImageSource imageSource)
{
byte[] bytes = null;
var bitmapSource = imageSource as BitmapSource;
if (bitmapSource != null)
{
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
using (var stream = new MemoryStream())
{
encoder.Save(stream);
bytes = stream.ToArray();
}
}
return bytes;
}
public static byte[] ConvertBitmapSourceToByteArray(BitmapSource image)
{
byte[] data;
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
public static byte[] ConvertBitmapSourceToByteArray(ImageSource imageSource)
{
var image = imageSource as BitmapSource;
byte[] data;
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
public static byte[] ConvertBitmapSourceToByteArray(Uri uri)
{
var image = new BitmapImage(uri);
byte[] data;
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
public static byte[] ConvertBitmapSourceToByteArray(string filepath)
{
var image = new BitmapImage(new Uri(filepath));
byte[] data;
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
public static BitmapImage ConvertByteArrayToBitmapImage(Byte[] bytes)
{
var stream = new MemoryStream(bytes);
stream.Seek(0, SeekOrigin.Begin);
var image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
return image;
}
}
I want to add an image to the database in an image column in byte form
I am using SQLite to save my database data and WPF Application using dbContext c# to write my code
can anyone help me please?
private void ChooseImageButtonClick(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "Choose Image(*.JPG;*.PNG;*.GIF)|*.jpg;*.png;*.gif";
if (dlg.ShowDialog() == true)
{
string FileName = dlg.FileName.ToString();
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(FileName);
bitmap.EndInit();
ImageBox.Source = bitmap;
}
}
private void savebtnClick(object sender, RoutedEventArgs e)
{
using (DatabaseContext dbContext = new DatabaseContext())
{
Person p = new Person
{
Id = int.Parse(Idtextbox.Text),
Name = Nametextbox.Text,
Image = image
};
dbContext.Person.Add(p);
dbContext.SaveChanges();
RefreshList();
}
}
Just convert BitmapImage to byte array first
byte[] image;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 100;
using (MemoryStream ms = new MemoryStream())
{
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)ImageBox.Source));
encoder.Save(ms);
image = ms.ToArray();
}
encoder = null;
And in your database context - add
using (DatabaseContext dbContext = new DatabaseContext())
{
Part part = new Part();
part.Id = int.Parse(TextBoxID.Text);
part.Name = TextBoxName.Text;
part.Image = image;
dbContext.Part.Add(part);
dbContext.SaveChanges();
RefreshPartsList();
}}
To convert byte array back to BitmapImage :
byte[] imageData = part.Image; // that you get from db
if (imageData == null || imageData.Length == 0)
{
//Show error msg or return here;
return;
}
var image = new BitmapImage();
using (var ms = new System.IO.MemoryStream(imageData))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = ms;
image.EndInit();
image.Freeze();
}
Add Property in 'Part' class
public byte[] ImageCol { get; set; }
Then from "OpenFileDialog" create Image from selected file. For Example
OpenFileDialog openFileDialog = new OpenFileDialog
{
Filter = "Image Files(*.BMP;*.JPG;*.JPEG;*.GIF;*.PNG)|*.BMP;*.JPG;*.JPEG;*.GIF;*.PNG",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
if (openFileDialog.ShowDialog()==DialogResult.OK)
{
var imageFromFile = System.Drawing.Image.FromFile(openFileDialog.FileName);
part.ImageCol = imageFromFile.ConvertBitmapImagetoBytes();
}
Convert BitMap to byte[]
public static byte[] ConvertBitmapImagetoBytes(this Image image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
It's always stop at the end of RawFormat, what did I do wrong?
private void genImgBtn_Click(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
Image gambar = pictureBox1.Image;
using (MemoryStream ms = new MemoryStream())
{
gambar.Save(ms,gambar.RawFormat);
byte[] imageBytes = ms.ToArray();
qrtext.Text = Convert.ToBase64String(imageBytes);
}
}
else
{
MessageBox.Show("Silahkan pilih gambar terlebih dahulu");
}
}
The program stops and asks for not giving null value. I don't know what should I do to resolve this.
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;
}
i need to convert the images(fetching from web service) into base64String to store them in the SQLite database.
EDIT: I use ImageOpened so that the image is loaded/downloaded before I convert them into base64String but ImageOpened doest run. How do I achieve this task ? I mean to convert array of images into base64.
this is my code:
public async void LoadData()
{
//get Json
string str = await Helper.getJSON();
//Deserialize json
MainClass apiData = JsonConvert.DeserializeObject<MainClass>(str);
//the problem loop
for (int i = 0; i < apiData.Categories.Count;i++ )
{
//apiData.Categoriesp[i].icon_image is the url of the image
BitmapImage image = new BitmapImage(new Uri(apiData.Categories[i].icon_image,UriKind.RelativeOrAbsolute));
//it never runs
image.ImageOpened += (s, e) =>
{
//code for conversion of image into memory stream
image.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
//setting imageInSql property of the list (but it never runs)
apiData.Categories[i].imageInSql = base64String;
};
}
//Inserting into database
using(var db= new SQLiteConnection(App.dbPath)){
//geting null in imageinSql property.
db.InsertAll(apiData.Categories,typeof(Category));
}
}
Thanks in advance.
For me it looks like a you are setting CreateOptions property inside the event handler.
image.ImageOpened += (s, e) =>
{
//code for conversion of image into memory stream
image.CreateOptions = BitmapCreateOptions.None;
You should do this like-
image.CreateOptions = BitmapCreateOptions.None;
image.ImageOpened += (s, e) =>
{
Try below code.
public async void LoadData()
{
//get Json
string str = await Helper.getJSON();
//Deserialize json
MainClass apiData = JsonConvert.DeserializeObject<MainClass>(str);
//the problem loop
for (int i = 0; i < apiData.Categories.Count;i++ )
{
//apiData.Categoriesp[i].icon_image is the url of the image
BitmapImage image = new BitmapImage(new Uri(apiData.Categories[i].icon_image,UriKind.RelativeOrAbsolute));
image.CreateOptions = BitmapCreateOptions.None
//it never runs
image.ImageOpened += (s, e) =>
{
//code for conversion of image into memory stream
WriteableBitmap wb = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
//setting imageInSql property of the list (but it never runs)
apiData.Categories[i].imageInSql = base64String;
};
}
//Inserting into database
using(var db= new SQLiteConnection(App.dbPath)){
//geting null in imageinSql property.
db.InsertAll(apiData.Categories,typeof(Category));
}
}