how to save byte[] image in custom folder in webapi? - asp.net-web-api

i have one model contain image ,i send model from angularjs and get model in webapi ,my method in web api
public IHttpActionResult Post([FromBody]Game model)
{
Image img = LoadImage(model.Image);
Game game = model;
_repository.Add<Game>(game);
return Ok();
}
public Image LoadImage(string imageName)
{
string[] str = imageName.Split(',');
byte[] bytes = Convert.FromBase64String(str[1]);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
but this code just return base64 to image,i want save jpg on custom folder in project

this code solve your problem
public IHttpActionResult Post([FromBody]Game model)
{
var image = SaveImage(model.Image, Guid.NewGuid().ToString());
model.Image = image; // set image name in model
_repository.Add<Game>(model);
return Ok();
}
public string SaveImage(string ImgStr, string ImgName)
{
String path = HttpContext.Current.Server.MapPath("~/images/Games"); //Path
//Check if directory exist
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
}
string imageName = ImgName + ".jpg";
//set the image path
string imgPath = Path.Combine(path, imageName);
string[] str = ImgStr.Split(',');
byte[] bytes = Convert.FromBase64String(str[1]);
File.WriteAllBytes(imgPath, bytes);
return imageName;
}

Related

How can I save an image in sqliteconnection xamarin forms [duplicate]

I have the following two methods that handles taking photos from a camera and picking photos from a library. They're both similar methods as at the end of each method, I get an ImageSource back from the Stream and I pass it onto another page which has an ImageSource binding ready to be set. These two method work perfectly. The next step now is to save the Image in SQLite so I can show the images in a ListView later on. My question for the XamGods (Xamarin Pros =), what is the best way to save image in SQLite in 2019? I have been in the forums for hours and I still don't have a tunnel vision on what I want to do. I can either
Convert Stream into an array of bytes to save in Sqlite.
Convert ImageSource into an array of bytes (messy/buggy).
Somehow retrieve the actual Image selected/taken and convert that into an array of bytes into SQLite
I'm sorry if my question is general, but Xamarin does not provide a clear-cut solution on how to save images in SQLite and you can only find bits and pieces of solutions throughout the forums listed below.
How to save and retrieve Image from Sqlite
Load Image from byte[] array.
Creating a byte array from a stream
Thank you in advance!
private async Task OnAddPhotoFromCameraSelected()
{
Console.WriteLine("OnAddPhotoFromCameraSelected");
var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { });
var stream = photo.GetStream();
photo.Dispose();
if (stream != null)
{
ImageSource cameraPhotoImage = ImageSource.FromStream(() => stream);
var parms = new NavigationParameters();
parms.Add("image", cameraPhotoImage);
var result = await NavigationService.NavigateAsync("/AddInspectionPhotoPage?", parameters: parms);
if (!result.Success)
{
throw result.Exception;
}
}
}
private async Task OnAddPhotoFromLibrarySelected()
{
Console.WriteLine("OnAddPhotoFromLibrarySelected");
Stream stream = await DependencyService.Get<IPhotoPickerService>().GetImageStreamAsync();
if (stream != null)
{
ImageSource selectedImage = ImageSource.FromStream(() => stream);
var parms = new NavigationParameters();
parms.Add("image", selectedImage);
parms.Add("stream", stream);
var result = await NavigationService.NavigateAsync("/AddInspectionPhotoPage?", parameters: parms);
if (!result.Success)
{
throw result.Exception;
}
}
}
As Jason said that you can save image path into sqlite database, but if you still want to save byte[] into sqlite database, you need to convert stream into byte[] firstly:
private byte[] GetImageBytes(Stream stream)
{
byte[] ImageBytes;
using (var memoryStream = new System.IO.MemoryStream())
{
stream.CopyTo(memoryStream);
ImageBytes = memoryStream.ToArray();
}
return ImageBytes;
}
Then load byte[] from sqlite, converting into stream.
public Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
For simple sample, you can take a look:
Insert byte[] in sqlite:
private void insertdata()
{
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "sqlite1.db3");
using (var con = new SQLiteConnection(path))
{
Image image = new Image();
image.Content = ConvertStreamtoByte();
var result = con.Insert(image);
sl.Children.Add(new Label() { Text = result > 0 ? "insert successful insert" : "fail insert" });
}
}
Loading image from sqlite:
private void getdata()
{
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "sqlite1.db3");
using (var con = new SQLiteConnection(path))
{
var image= con.Query<Image>("SELECT content FROM Image ;").FirstOrDefault();
if(image!=null)
{
byte[] b = image.Content;
Stream ms = new MemoryStream(b);
image1.Source = ImageSource.FromStream(() => ms);
}
}
}
Model:
public class Image
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string FileName { get; set; }
public byte[] Content { get; set; }
}

Xamarin Forms save image from an url into device's gallery

I am working on Xamarin Forms (with iOS and Android). What I want to do is to allow users to download image from an url by using DependencyService. I tried run in IOS emulator and the image did save into the emulator but does not show up in the gallery.
Appreciate help in that and following is my code:
In ViewModel:
public void DownloadImage()
{
IFileService fileSvc = DependencyService.Get<IFileService>();
WebClient wc = new WebClient();
byte[] bytes = wc.DownloadData(ImgUrl);
Stream stream = new MemoryStream(bytes);
fileSvc.SavePicture(DateTime.Now.ToString(), stream, "temp");
}
In Xamarin.iOS
public void SavePicture(string name, Stream data, string location = "temp")
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string imageFilename = Path.Combine(documentsPath, "Images", location);
Directory.CreateDirectory(imageFilename);
string filePath = Path.Combine(documentsPath, name);
byte[] bArray = new byte[data.Length];
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
using (data)
{
data.Read(bArray, 0, (int)data.Length);
}
int length = bArray.Length;
fs.Write(bArray, 0, length);
}
}
In Xamarin.Droid
public void SavePicture(string name, Stream data, string location = "temp")
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
documentsPath = Path.Combine(documentsPath, "Images", location);
Directory.CreateDirectory(documentsPath);
string filePath = Path.Combine(documentsPath, name);
byte[] bArray = new byte[data.Length];
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
using (data)
{
data.Read(bArray, 0, (int)data.Length);
}
int length = bArray.Length;
fs.Write(bArray, 0, length);
}
}
If you Want to save image into Gallery, please follow the code below.
Firstly, create Create the IMediaService Interface in PCL.
public interface IMediaService
{
void SaveImageFromByte(byte[] imageByte,string filename);
}
Then implement this interface in Platform-specific
Xamarin.Android Project
public class MediaService : IMediaService
{
Context CurrentContext => CrossCurrentActivity.Current.Activity;
public void SaveImageFromByte(byte[] imageByte, string filename)
{
try
{
Java.IO.File storagePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
string path = System.IO.Path.Combine(storagePath.ToString(), filename);
System.IO.File.WriteAllBytes(path, imageByte);
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(path)));
CurrentContext.SendBroadcast(mediaScanIntent);
}
catch (Exception ex)
{
}
}
}
implement this interface in Platform-specific
Xamarin.iOS Project
public class MediaService : IMediaService
{
public void SaveImageFromByte(byte[] imageByte,string fileName)
{
var imageData = new UIImage(NSData.FromArray(imageByte));
imageData.SaveToPhotosAlbum((image, error) =>
{
//you can retrieve the saved UI Image as well if needed using
//var i = image as UIImage;
if (error != null)
{
Console.WriteLine(error.ToString());
}
});
}
}
For accessing the CurrentContext Install the NuGet Package (Plugin.CurrentActivity) from NuGet Package Manager, also check for the external storage permission.

How to get Image from directory path in xamarin forms

I want to retrieve image which i have it's path in phone
filepath = "/storage/emulated/0/Android/data/com.CommunicatorEye/files/Pictures/EmployeesCards/IMG_20190131_143513.jpg";
var image = DependencyService.Get<IDependency().RetriveImageFromLocation(filepath);
IDependency.cs
public interface IDependency
{
Task<Image> RetriveImageFromLocation(string location);
}
Android
DependencyImplementation.cs
public async Task<Image> RetriveImageFromLocation(string location)
{
Image image = new Image();
var memoryStream = new MemoryStream();
using (var source = System.IO.File.OpenRead(location))
{
await source.CopyToAsync(memoryStream);
}
image.Source = ImageSource.FromStream(() => memoryStream);
return image;
}
but it doesn't work for me , any sample ?
If that file is within your app's sandbox, there is no reason to use DI/DependencyService/etc... to obtain a stream to populate an ImageSource and then add that to an Image.
Use an FileImageSource (static ImageSource.FromFile) and supply it the path:
var image = new Image
{
Source = ImageSource.FromFile(filePath)
};
This is how you can get path of resources. keys should be declared in App.xaml file
public static String GetImagePath(string AppResourceName)
{
return (Application.Current.Resources[AppResourceName] as FileImageSource).File;
}
public static Color GetColor(string AppResourceName)
{
return (Color)Application.Current.Resources[AppResourceName];
}

Best approach to download image

I have a simple site (WebAPI) that returns a bunch of albums in the get method. Each album has attributes such as title, artist and so on. The attribute under here is the image (album photo) attribute. Each album has an image, what is the best way to send the image back to client. Should it be sent as binary data as part of the album object for example like
Public Class Album
{
string title;
byte[] image;
}
Or should I send the path to the image in the Album object and have the client download the image separately?
Like
Public Class Album
{
string title;
string imagePath;
}
You can see this post The downloaded file as stream in controller (ASP.NET MVC 3) will automatically disposed? as reference.
You can use FileStream.
protected override void WriteFile(HttpResponseBase response) {
// grab chunks of data and write to the output stream
Stream outputStream = response.OutputStream;
using (FileStream) {
byte[] buffer = new byte[_bufferSize];
while (true) {
int bytesRead = FileStream.Read(buffer, 0, _bufferSize);
if (bytesRead == 0) {
// no more data
break;
}
outputStream.Write(buffer, 0, bytesRead);
}
}
}
Instead of passing
Public class Album
{
string title;
byte[] image;
}
back to the client, I would change image to a int imageId:
Public class Album
{
string Title{get;set};
int ImageId{get;set};
}
Then create a WebApi controller that handles images with a method written like this:
public async Task<HttpResponseMessage> Get(HttpRequestMessage request, int imageId)
{
byte[] img = await _myRepo.GetImgAsync(imageId);
HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(img)
};
msg.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return msg;
}

download pdf files stored in database in mvc3

I store few pdf files in my db as binary format using the below code in my controller,
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
Image newImage = new Image();
newImage.MimeType = file.ContentType;
var binaryReader = new BinaryReader(file.InputStream);
newImage.Data = binaryReader.ReadBytes(file.ContentLength);
binaryReader.Close();
objImage.InsertImage(newImage.Data);
return View();
}
now i want to download them back based on the id passed to the contrller that pdf files should be downloaded??
this is my code for pdf download, wat do i need to add more
public ActionResult Download(int id)
{
DataSet da = new DataSet();
da = objImage.getUserImage(id);
DataTable dt = new DataTable();
dt = da.Tables[0];
Byte[] imagedata=(Byte[])dt.Rows[0]["UsImage"];
}
this is my code for pdf download, wat do i need to add more
Return an ActionResult:
public ActionResult Download(int id)
{
...
byte[] imagedata = (byte[])dt.Rows[0]["UsImage"];
return File(imagedata, "image/png");
}
and if you want the browser to popup a Save As dialog instead of displaying the image inline specify a filename:
public ActionResult Download(int id)
{
...
byte[] imagedata = (byte[])dt.Rows[0]["UsImage"];
return File(imagedata, "image/png", "foo.png");
}
Obviously the MIME type and the filename could come from your database as well. In this example I have hardcoded them but you could adapt this code.
return File(result.Content, result.Extension.Replace(".", ""));
public ActionResult Download(int id)
{
DataSet da = new DataSet();
da = objImage.getUserImage(id);
DataTable dt = new DataTable();
dt = da.Tables[0];
Byte[] imagedata=(Byte[])dt.Rows[0]["UsImage"];
return File(imagedata, "image/png");
}
public ActionResult GetPdf(int id)
{
ProjectProfile projectprofile = db.ProjectProfiles.Find(id);
var image = projectprofile.pdf;
return File(image, "application/pdf");
}

Resources