I'm new in programming in Windows Phone (and StackOverflow tbh). Currently, I'm working on a task that concerns with sending images stored in the Windows Phone's storage (with Exif info) to a Java server. So far I have successfully send the byte stream from the Windows Phone client and construct the image on the Java side, however, the Exif information is somehow lost. I believe it's just the way I send it on Windows Phone that's causing the problem. Very much appreciated for any help or guidance !
Here's my code on the Windows Phone client:
// Windows Phone Client code (MainPage.xaml.cs)
// This function is called when an image is selected from
// the task PhotoChooserTask ptask, which brings
// a popup that allows the user to choose an image
// from the phone's storage
void ptask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK && e.ChosenPhoto != null)
{
//Take JPEG stream and decode into a WriteableBitmap object
App.CapturedImage = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
// Attempt to send the image
WriteableBitmap pic = new WriteableBitmap(App.CapturedImage);
MemoryStream stream = new MemoryStream();
pic.SaveJpeg(stream, App.CapturedImage.PixelHeight, App.CapturedImage.PixelWidth, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
client.Send(stream);
// Close the socket connection explicitly
client.Close();
}
}
Here's the code in the SocketClient.cs
public string Send(MemoryStream data)
{
byte[] msData = data.ToArray();
if (_socket != null)
{
// Create SocketAsyncEventArgs context object
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
// Set properties on context object
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
socketEventArg.UserToken = null;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
_clientDone.Set();
});
// Add the data to be sent into the buffer
socketEventArg.SetBuffer(msData, 0, msData.Length);
// Sets the state of the event to nonsignaled, causing threads to block
_clientDone.Reset();
// Make an asynchronous Send request over the socket
_socket.SendAsync(socketEventArg);
}
else
{
response = "Socket is not initialized";
}
return response;
}
On the Java Server,
public static void main(String[] args) {
ServerSocket serverSocket;
Socket client;
try {
serverSocket = new ServerSocket(PORT_NUMBER);
while (true) {
client = serverSocket.accept();
// Extract exif info
InputStream inputStream = client.getInputStream();
InputStream stream = new BufferedInputStream(inputStream);
// Create file from the inputStream
File file = new File("image.jpg");
try {
OutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[4096];
for (int n; (n = stream.read(buffer)) != -1;) {
os.write(buffer, 0, n);
}
}
The output image is identical to the one sent from the windows phone, just without any Exif information whatsoever. Anyone could point out what I did wrong that causes the information to be lost? I'm guessing because I called the SaveJpeg function in the windows phone code, rewriting the image file, and losing all information there, but I don't know how else to convert the image to byte and stream it.
Much help is appreciated ! Thank you.
I found the answer to my own problem. For those of you who might have a problem with this. I simply use:
Byte[] imageData = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Position = 0;
e.ChosenPhoto.Read(imageData, 0, imageData.Length);
Then send the byte array in my send function:
socketEventArg.SetBuffer(imageData, 0, imageData.Length);
Related
Hello, would any of you send a working code to download a photo from a given http address on android Xamarin c #?
First, I need to create a new folder for my application files.
My goal is to download the file from the internet to my Android folder (saving this file with its original name is best).
The next step is to display the image from that folder in "ImageView". It is also important that there are permissions in android and I do not fully understand it.
Could any of you send it to me or help me understand it and explain the topic?
*Actually i have this code:
string address = "https://i.stack.imgur.com/X3V3w.png";
using (WebClient webClient = new WebClient())
{
webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;
webClient.DownloadFile(address, Path.Combine(pathDire, "MyNewImage1.png"));
//System.Net.WebException: 'An exception occurred during a WebClient request.'
}
Loading image from url and display in imageview.
private void Btn1_Click(object sender, System.EventArgs e)
{
var imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/devices.png");
imagen.SetImageBitmap(imageBitmap);
}
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
SavePicture("ImageName.jpg", imageBytes, "imagesFolder");
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
download image and save it in local storage.
private void SavePicture(string name, byte[] data, string location = "temp")
{
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
documentsPath = System.IO.Path.Combine(documentsPath, "Orders", location);
Directory.CreateDirectory(documentsPath);
string filePath = System.IO.Path.Combine(documentsPath, name);
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
int length = data.Length;
fs.Write(data, 0, length);
}
}
you need to add permission WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE in AndroidMainfeast.xml, then you also need to Runtime Permission Checks in Android 6.0.
private void checkpermission()
{
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted)
{
// We have permission, go ahead and use the writeexternalstorage.
}
else
{
// writeexternalstorage permission is not granted. If necessary display rationale & request.
}
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) == (int)Permission.Granted)
{
// We have permission, go ahead and use the ReadExternalStorage.
}
else
{
// ReadExternalStorage permission is not granted. If necessary display rationale & request.
}
}
I need to create a PDF file in memory within a web API and send it. I do create the PDF and the web API sends it, but I can't open it once received.
I do create the PDF as a byte array with this:
private byte[] createPDF()
{
MemoryStream memStream = new MemoryStream();
byte[] pdfBytes;
Document doc = new Document(iTextSharp.text.PageSize.LETTER);
PdfWriter wri = PdfWriter.GetInstance(doc, memStream);
doc.AddTitle("test");
doc.AddCreator("I am");
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
pdfBytes = memStream.ToArray();
doc.Close(); //Close
return pdfBytes;
}
This method is called by the method in the web API which sends the PDF, and it is this one:
[HttpGet]
public HttpResponseMessage GetFiniquitopdf()
{
try
{
byte[] buffer = createPDF();
response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(new MemoryStream(buffer));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentLength = buffer.Length;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "myFirstPDF.pdf"
};
}
catch (Exception e)
{
response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
return response;
}
The problem is when the PDF is downloaded it is useless, can't be opened, I don't understand why the PDF can't be opened, I thought it was the security of the Windows 10, so once downloaded I do check it as a secure file, but it doesn't open anyway.
I guess there is something wrong in the way I send it or maybe I lack of something in the creation of the PDF file
thanks in advance
You retrieve the bytes from the memory stream before closing the document:
pdfBytes = memStream.ToArray();
doc.Close(); //Close
return pdfBytes;
But the pdf in the memory stream is not complete before the document is closed. Thus, simply switch the order of instructions:
doc.Close(); //Close
pdfBytes = memStream.ToArray();
return pdfBytes;
I will working on the Recording functionality in my windows phone 7 app.
I implemented the Recording functionality through this reference link.
It completely works fine at there and in my case also.
Actually the scenario is, In my application i created first page that will works as the recording screen as same as above referred link.
and when we stop the recording i redirected to the second page and saved that recording in Isolated storage and at the second page i bound the recorded sounds. At here i played the recorded sounds at it works fine.
Now, when i m again go to the recording screen(first page) and starts another recording. it will some times records fine and some times it will skip the some sounds during recording as like beep sounds and it will looks like a extra noise in recording and not getting properly recording sounds.
My Code is like,
public partial class NikhilRecord : PhoneApplicationPage
{
//XNA Objects for Record And Playback
Microphone mphone;
//Used for Storing captured buffers
List<byte[]> memobuffercollection = new List<byte[]>();
//Used for displaying stored memos
ObservableCollection<MemoInfo> memofiles = new ObservableCollection<MemoInfo>();
SpaceTime spaceTime = new SpaceTime();
public NikhilRecord()
{
InitializeComponent();
//Create new Microphone and set event handler.
mphone = Microphone.Default;
mphone.BufferReady += OnMicrophoneBufferReady;
String FileName = PhoneApplicationService.Current.State["MySelectedSong"].ToString();
using (IsolatedStorageFile IsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
using (IsolatedStorageFileStream fileStream = IsolatedStorage.OpenFile(FileName, FileMode.Open, FileAccess.Read))
{
MyMedia.SetSource(fileStream);
MyMedia.CurrentStateChanged += new RoutedEventHandler(mediaPlayer_CurrentStateChanged);
fileStream.Close();
fileStream.Dispose();
//Start Recording
OnRecordButtonClick();
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
void UpdateRecording(bool isRecording)
{
if (!isRecording)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
spaceTime.Space = storage.AvailableFreeSpace;
}
}
else
{
spaceTime.Space = memobuffercollection.Count * mphone.GetSampleSizeInBytes(mphone.BufferDuration);
}
spaceTime.Time = mphone.GetSampleDuration((int)Math.Min(spaceTime.Space, Int32.MaxValue));
}
void OnMicrophoneBufferReady(object sender, EventArgs e)
{
// Get buffer from microphone and add to collection
byte[] buffer = new byte[mphone.GetSampleSizeInBytes(mphone.BufferDuration)];
int bytesreturned = mphone.GetData(buffer);
memobuffercollection.Add(buffer);
UpdateRecording(true);
// To be Continue...
if (spaceTime.Time > TimeSpan.FromMinutes(10))
{
StopRecording();
UpdateRecording(false);
}
}
void OnRecordButtonClick()
{
if (mphone.State == MicrophoneState.Stopped)
{
// Clear the collection for storing the buffers
memobuffercollection.Clear();
// Start Recording
mphone.Start();
MyMedia.Play();
}
else
{
MyMedia.Stop();
//mphone.Stop();
PopUpGrid.Visibility = Visibility.Visible;
RecordGrid.Opacity = 0.5;
RecordGrid.IsHitTestVisible = false;
}
bool isRecording = mphone.State == MicrophoneState.Started;
UpdateRecording(isRecording);
}
void StopRecording()
{
// Get the last partial buffer
int sampleSize = mphone.GetSampleSizeInBytes(mphone.BufferDuration);
byte[] extraBuffer = new byte[sampleSize];
int extraBytes = mphone.GetData(extraBuffer);
// Stop Recording
mphone.Stop();
//Stop the Song
MyMedia.Stop();
// Create MemoInfo object and add at top of collection
int totalSize = memobuffercollection.Count * sampleSize + extraBytes;
TimeSpan duration = mphone.GetSampleDuration(totalSize);
MemoInfo memoInfo = new MemoInfo(DateTime.UtcNow, totalSize, duration);
memofiles.Insert(0, memoInfo);
// Save Data in IsolatedStorage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] alldirectories = storage.GetDirectoryNames("NikDirectory");
if (alldirectories.Count() == 0)
storage.CreateDirectory("NikDirectory");
try
{
using (IsolatedStorageFileStream stream = storage.CreateFile("NikDirectory\\" + memoInfo.FileName))
{
// Write buffers from collection
foreach (byte[] buffer in memobuffercollection)
stream.Write(buffer, 0, buffer.Length);
// Write partial buffer
stream.Write(extraBuffer, 0, extraBytes);
stream.Close();
stream.Dispose();
}
Uri url = new Uri("/Gallery.xaml", UriKind.Relative);
NavigationService.Navigate(url);
memobuffercollection.Clear();
}
catch (Exception ees)
{
MessageBox.Show(ees.Message);
Uri url = new Uri("/Karaoke.xaml", UriKind.Relative);
NavigationService.Navigate(url);
}
}
bool isRecording = mphone.State == MicrophoneState.Started;
UpdateRecording(isRecording);
}
}
So, please help me out the problem. I heard at somewhere that you have to dispose all the objects of the microphone when you redirect to another screen. is it true ? or anything else.
Please help me.
Looking Forward.
Instead of using a collection, you should use following way to read your recorded bytes.
This should be done into the BufferReady event of your microphone object.
byte[] audioBuffer = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)];
microphone.GetData(audioBuffer);
RecordingStream.Write(audioBuffer, 0, audioBuffer.Length);
RecordingStream is a MemoryStream , should be declared globally.
I am not sure about this but as I have used it and it works completely fine in each case.
Try this.
I saved the image in MediaLibrary as follow
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, msWrite, g_IntWidth, g_IntHeight, 0, 100);
MediaLibrary ML = new MediaLibrary();
ML.SavePicture("My1stPhoto.jpg", msWrite);
The problem is :
later when I use PhotoChooser to select previously saved Photo ( My1stPhoto.jpg ), but this is working. It seems the return filename is not the same as My1stPhoto.jpg
I used below code , the byte is 0 ? Need your help. Thanks.
void photoChooserTask_Completed(object sender, PhotoResult e)
{
strSelectedFilenameinHub = e.OriginalFileName;
StreamResourceInfo sri = null;
Uri jpegUri = new Uri( strSelectedFilenameinHub, UriKind.Relative);
sri = Application.GetResourceStream(jpegUri);
byte[] imageData = new byte[sri.Stream.Length];
sri.Stream.Read(imageData, 0, System.Convert.ToInt32(sri.Stream.Length));
}
Why would you want to retrieve the stream using the media library? You can use directly e.ChosenPhoto to retrieve the contents of the picture:
void photoChooserTask_Completed(object sender, PhotoResult e)
{
byte[] imageData = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(imageData, 0, System.Convert.ToInt32(e.ChosenPhoto.Length));
}
I also doubt that you need to copy the contents of the stream to a byte array. Depending on what you want to do with the picture, you may want to choose a less memory-consuming way.
I'm using the Blackberry JDE (9000 simulator), and am wondering if I can display an image from the web.
Currently, I'm seeing tutorials that use Bitmap.getBitmapResource to display images that are local to the blackberry application, but looking at the API, I'm not seeing any support for giving a web URL.
Are there other Blackberry image classes I can check out? Or is this feature just not supported?
You can download image using HTTPConnection and InputStream, create EncodedImage from stream and then display it.
See coderholic - Blackberry WebBitmapField
BTW, you can use IOUtilities.streamToBytes() method to read bytes from InputStream directly!
Here is a code example for your problem:
HttpConnection httpConn = null;
InputStream inputStream = null;
int ResponseCode = HttpConnection.HTTP_OK;
byte[] ResponseData = null;
try {
httpConn = (HttpConnection) Connector.open(url, Connector.READ, true);
ResponseCode = httpConn.getResponseCode();
if (ResponseCode == HttpConnection.HTTP_OK) {
inputStream = httpConn.openInputStream();
ResponseData = IOUtilities.streamToBytes(inputStream);
}
}
catch(IOException e){
throw new IOException("HTTP response code: "
+ ResponseCode);
}
finally {
try {
inputStream.close();
inputStream = null;
httpConn.close();
httpConn = null;
}
catch(Exception e){}
}
return ResponseData;
If you want code that made to exactly do this (though this post is old, so I'm guessing you don't anymore)
Here