how to save an image from UWP into MYsql using php - c#

It's my first time developing on UWP and I can't add an image into Mysql database using PHP and I must add its' path in the database.
I can't use sqlite or any other database as my collegues started already using Mysql.
Can anyone please help me or give an example
I wouLd really appreciate your help (i'm stuck here )
So, here is my UWP code that I used to upload the chosen image from my gallery
private Stream stream = new MemoryStream();
private CancellationTokenSource cts;
public MainPage()
{
this.InitializeComponent();
}
private async void buttonUpload_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker open = new FileOpenPicker();
open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
open.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
open.FileTypeFilter.Clear();
open.FileTypeFilter.Add(".bmp");
open.FileTypeFilter.Add(".png");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".jpg");
// Open a stream for the selected file
StorageFile file = await open.PickSingleFileAsync();
// Ensure a file was selected
if (file != null)
{
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
fileStream.AsStream().CopyTo(stream);
img.Source = bitmapImage;
}
}
}
private async void submit_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("http://localhost/mydatabase/add.php");
HttpClient client = new HttpClient();
HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream());
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = streamContent;
HttpResponseMessage response = await client.PostAsync(uri, streamContent).AsTask(cts.Token);
`
and here is the php i'm using
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$UserName = $_POST['UserName'];
$UserImage = $_POST['UserImage'];
require_once('conn.php');
$sql ="SELECT UserId FROM user";
$res = mysqli_query($connect,$sql);
$UserId =0 ;
while($row = mysqli_fetch_array($res)){
$UserId = $row['UserId'];
$UserId = $UserId+1;
}
$path = "UserImage/$UserId.png";
$actualpath = "http://localhost/mydatabase/$path";
$sql = "INSERT INTO user (UserId,UserName,UserImage) VALUES ('$UserId','$UserName','$actualpath')";
if(mysqli_query($connect,$sql)){
file_put_contents($path,base64_decode($UserImage));
echo "Successfully Uploaded";
}
mysqli_close($connect);
}else{
echo "Error";
}
?>
And all what i get is empty images in the folder I created ... apparently I have a problem after uploading the image from the UWP, but I'm not sure about that.

Read the file using PHP and insert that into the database.
Keep in mind, the bigger the image the longer the string.
$data = file_get_contents('/pics/item.png');
return $data;
This would return the data(from the picture)

Related

Problem accessing a file even with broadFileSystemAccess enabled

I have a UWP Desktop application that has text and audio files associated, for example when the user selects the Class1.txt file, the application automatically tries to open the Class1.mp3 file.
Even with broadFileSystemAccess configured, the operation always returns an access denied error.
Any help is most welcome. Thanks.
private async void nviOpen_Tapped(object sender, TappedRoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".txt");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
try
{
using (var txtStream = await file.OpenStreamForReadAsync())
{
var encoding = FileEncoding.DetectFileEncoding(txtStream);
txtStream.Seek(0, SeekOrigin.Begin);
var stmReader = new StreamReader(txtStream, encoding);
var txtContent = await stmReader.ReadToEndAsync();
tbxOriginalText.Text = txtContent;
}
//Open associated audio file
var audioFile = await StorageFile.GetFileFromPathAsync(file.Path + #"\" + file.DisplayName + ".mp3");
if (audioFile != null)
{
MediaPlaybackItem mediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(audioFile));
}
}
catch (Exception ex)
{
MessageDialog msgDlg = new MessageDialog(ex.Message);
await msgDlg.ShowAsync();
}
}
}
Please take a look at the file system privacy setting and make sure that you've allowed your app for accessing your file system.
Like this:

How to convert an Image URL into a StorageFile?

I am working with Unsplash API to get Images. When I send the request for an Image, part of the answer is the Image URL which looks like this:
https://images.unsplash.com/photo-1535159530326-d7bf54bfb24e?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjM1NDkzfQ&s
I was able to make this URL a BitmapImage and make it an Image Source in the app UI. But I was not able to download it to make it a StorageFile.
How can I download the image from this kind of URL and/or make it a StorageFile?
The following code will download the file into local storage, and then give you a Uri that you can use to set the Image Source:
private async Task<String> DownloadImage(string url, String fileName)
{
const String imagesSubdirectory = "DownloadedImages";
var rootFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(imagesSubdirectory, CreationCollisionOption.OpenIfExists);
var storageFile = await rootFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (HttpClient client = new HttpClient())
{
byte[] buffer = await client.GetByteArrayAsync(url);
using (Stream stream = await storageFile.OpenStreamForWriteAsync())
stream.Write(buffer, 0, buffer.Length);
}
// Use this path to load image
String newPath = String.Format("ms-appdata:///local/{0}/{1}", imagesSubdirectory, fileName);
return newPath;
}
// Here is an example of how to use the new DownloadImage() method
private async void Button_Download(object sender, RoutedEventArgs e)
{
var uniqueFileName = $#"{Guid.NewGuid()}.jpg";
String newPath = await DownloadImage("https://images.unsplash.com/photo-1535159530326-d7bf54bfb24e?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjM1NDkzfQ&s=6dbf8e03a25f469d0f845992e6b2eb9e",
uniqueFileName);
myImage.Source = new BitmapImage(new Uri(newPath));
}

how to copy an image from the filepicker into anotehr folder via an UWP app?

I need to copy an image from my windows universal app, I was able to pick an image from my gallery but i don't how to copy it in another folder.
Although I was able to display the image in my UWP interface, so I think that I succeed to get it as a stream.
Any help would be appreciated, I'm lost here ... here is the code I used:
public MainPage()
{
this.InitializeComponent();
// Scenario4WriteableBitmap = new WriteableBitmap((int)Scenario4ImageContainer.Width, (int)Scenario4ImageContainer.Height);
Scenario2DecodePixelHeight.Text = "100";
Scenario2DecodePixelWidth.Text = "100";
}
private async void buttonUpload_Click(object sender, RoutedEventArgs e)
{
int decodePixelHeight=150;
int decodePixelWidth=150;
// Try to parse an integer from the given text. If invalid, default to 100px
if (!int.TryParse(Scenario2DecodePixelHeight.Text, out decodePixelHeight))
{
Scenario2DecodePixelHeight.Text = "100";
decodePixelHeight = 100;
}
// Try to parse an integer from the given text. If invalid, default to 100px
if (!int.TryParse(Scenario2DecodePixelWidth.Text, out decodePixelWidth))
{
Scenario2DecodePixelWidth.Text = "100";
decodePixelWidth = 100;
}
FileOpenPicker open = new FileOpenPicker();
open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
open.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
open.FileTypeFilter.Clear();
open.FileTypeFilter.Add(".bmp");
open.FileTypeFilter.Add(".png");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".jpg");
// Open a stream for the selected file
StorageFile file = await open.PickSingleFileAsync();
// Ensure a file was selected
if (file != null)
{
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.DecodePixelHeight = decodePixelHeight;
bitmapImage.DecodePixelWidth = decodePixelWidth;
await bitmapImage.SetSourceAsync(fileStream);
Scenario2Image.Source = bitmapImage;
}
}
}
private async void submit_Click(object sender, RoutedEventArgs e)
{
String url = "http://localhost/mydatabase/add.php";
var values = new List<KeyValuePair<String, String>>
{
new KeyValuePair<string, string>("UserName",UserName.Text),
new KeyValuePair<string, string>("UserImage",UserImage.Text),
};
HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.PostAsync(url, new FormUrlEncodedContent(values));
/*client.DefaultRequestHeaders.Add("content_type", "binary/octet_stream");
responseImage = client.PostAsync("", FileChooser.FileName);*/
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(response.StatusCode.ToString());
var dialog = new MessageDialog("added succesfully ");
await dialog.ShowAsync();
}
else
{
// problems handling here
string msg = response.IsSuccessStatusCode.ToString();
throw new Exception(msg);
}
}
catch (Exception exc)
{
// .. and understanding the error here
Debug.WriteLine(exc.ToString());
}
}
`
you can use CopyAsync of StorageFile to copy the file you get from FileOpenPicker to a specific folder.

C# WP8.1:Convert image from gallery to base64

I'm having a little trouble developing my app. What I'm trying to do now is that let the user pick their picture from gallery(picture album) and display it. Furthermore, I want to convert that picture taken to Base64 string. Right now I've successfully pull and display picture from gallery, is there anyway I can convert that picture to base64 string.
Here's the code how I grab and display
private void picprofile_Tapped(object sender, TappedRoutedEventArgs e)
{
CoreApplicationView view;
String ImagePath;
view = CoreApplication.GetCurrentView();
ImagePath = string.Empty;
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
filePicker.PickSingleFileAndContinue();
view.Activated += viewActivated;
}
private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
{
CoreApplicationView view;
view = CoreApplication.GetCurrentView();
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
StorageFile storageFile = args.Files[0];
var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
picprofile.ImageSource = bitmapImage;
}
}
See this code below help . I hope there are multiple ways to do this . The link might help you
public async Task<string> ImageToBase64(StorageFile MyImageFile)
{
Stream ms = await MyImageFile.OpenStreamForReadAsync();
byte[] imageBytes = new byte[(int)ms.Length];
ms.Read(imageBytes, 0, (int)ms.Length);
return Convert.ToBase64String(imageBytes);
}

setting picture in image UI element using file picker

In my app user can set profile pic from device memory i.e tablet memory or desktop local drive and upload it to server.
I used file picker so that user can select one picture and set it as profile picture, but the problem is the picture is not sticking to Image element.
My code:
private async void filePicker()
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
String filePath = file.Path;
System.Diagnostics.Debug.WriteLine(filePath);
Uri uri = new Uri(filePath, UriKind.Relative);
profilePicture.Source = new BitmapImage(uri);
}
}
internal bool EnsureUnsnapped()
{
// FilePicker APIs will not work if the application is in a snapped state.
// If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
bool unsnapped = ((ApplicationView.Value != ApplicationViewState.Snapped) || ApplicationView.TryUnsnap());
if (!unsnapped)
{
//NotifyUser("Cannot unsnap the sample.", NotifyType.StatusMessage);
}
return unsnapped;
}
the file path that I'm getting is this one
filePath=C:\Users\Prateek\Pictures\IMG_0137.JPG
I don't know what went wrong.
I am not sure if this will solve the problem, this is what I did to set my image source.
Using a bitmap image as the source to your image
BitmapImage bitmapimage = new BitmapImage();
StorageFile file = await openPicker.PickSingleFileAsync();
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
await bitmapimage.SetSourceAsync(stream);
profilePicture.Source = bitmapImage;
I have used this code ...
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
this.textBlock.Text =
"File Path: " + file.Path + Environment.NewLine +
"File Name: " + file.Name;
try
{
var stream = await file.OpenReadAsync();
var imageSource = new BitmapImage();
await imageSource.SetSourceAsync(stream);
this.image.Source = imageSource;
}
catch (Exception ex)
{
this.textBlock.Text = ex.ToString();
}
}
else
{
this.textBlock.Text = "Operation cancelled.";
}

Categories

Resources