I'm having a Windows 8 app which is working pretty well and now I want to write the same app for Windows Phone 8, but I'm only getting a black image and not the right image.
This is my code for uploading the image file
if ((_fileType == ".jpg" || _fileType == ".png" || _fileType == ".jpeg") && _fileSize < 3500000)
{
byte[] myPicArray = ConvertToBytes(_bmpFile);
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(MYURI);
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new ByteArrayContent(myPicArray);
form.Add(content, "media", _randomStringFileName + _fileType);
HttpResponseMessage response = await httpClient.PostAsync("upload.php", form);
}
and this is the code for converting my image to a byte array
private byte[] ConvertToBytes(BitmapImage bitmapImage)
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap
(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
// write an image into the stream
Extensions.SaveJpeg(btmMap, ms,
bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);
return ms.ToArray();
}
}
Has anybody an idea why I'm only getting a black image and not the right image? The image was selected by the PhotoChooseTask.
The PhotoChooseTask already gives you the Stream, so you'll just need to use that instead (You can't use the BitMap yet because it's still busy writing it to the device and generating thumbnails, etc)
PhotoResult photoResult = e as PhotoResult;
MemoryStream memoryStream = new MemoryStream();
photoResult.ChosenPhoto.CopyTo(memoryStream);
byte[] myPicArray = memoryStream.ToArray();
Related
I'm trying to upload files to an Azure fileshare using the library Azure.Storage.Files.Shares.
If I don't chunk the file (by making a single UploadRange call) it works fine, but for files over 4Mb I haven't been able to get the chunking working. The file is the same size when downloaded, but won't open in a viewer.
I can't set smaller HttpRanges on a large file as I get a 'request body is too large' error, so I'm splitting the filestream into multiple mini streams and uploading the entire HttpRange of each of these
ShareClient share = new ShareClient(Common.Settings.AppSettings.AzureStorageConnectionString, ShareName());
ShareDirectoryClient directory = share.GetDirectoryClient(directoryName);
ShareFileClient file = directory.GetFileClient(fileKey);
using(FileStream stream = fileInfo.OpenRead())
{
file.Create(stream.Length);
//file.UploadRange(new HttpRange(0, stream.Length), stream);
int blockSize = 128 * 1024;
BinaryReader reader = new BinaryReader(stream);
while(true)
{
byte[] buffer = reader.ReadBytes(blockSize);
if (buffer.Length == 0)
break;
MemoryStream uploadChunk = new MemoryStream();
uploadChunk.Write(buffer, 0, buffer.Length);
uploadChunk.Position = 0;
file.UploadRange(new HttpRange(0, uploadChunk.Length), uploadChunk);
}
reader.Close();
}
The code above uploads without error, but when downloading the image from Azure it is corrupt.
Does anyone have any ideas? Thanks for any help you can provide.
cheers
Steve
I was able to reproduce the issue. Basically the problem is with the following line of code:
new HttpRange(0, uploadChunk.Length)
Essentially you're always setting the content at the same range and that's why the file is getting corrupted.
Please try the code below. It should work. What I did here is defined the HTTP range offset and moving it constantly with number of bytes already written to the file.
using (FileStream stream = fileInfo.OpenRead())
{
file.Create(stream.Length);
//file.UploadRange(new HttpRange(0, stream.Length), stream);
int blockSize = 1 * 1024;
long offset = 0;//Define http range offset
BinaryReader reader = new BinaryReader(stream);
while (true)
{
byte[] buffer = reader.ReadBytes(blockSize);
if (buffer.Length == 0)
break;
MemoryStream uploadChunk = new MemoryStream();
uploadChunk.Write(buffer, 0, buffer.Length);
uploadChunk.Position = 0;
HttpRange httpRange = new HttpRange(offset, buffer.Length);
var resp = file.UploadRange(httpRange, uploadChunk);
offset += buffer.Length;//Shift the offset by number of bytes already written
}
reader.Close();
}
I am creating a project in which I want to compress image so that it can be uploaded easily on windows azure and later can be retrieved easily from windows azure to my application.So can you please help me with how can I do that. I am using BitmapImage right now . Follwoing is the code which I am using to upload image to azure
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bitmap);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveJpeg(stream, wb.PixelWidth, wb.PixelHeight, 0, 0);
AzureStorage storage = new AzureStorage();
storage.Account = **azure account**;
storage.BlobEndPoint = **azure end point**;
storage.Key = **azure key**;
string fileName = uid;
bool error = false;
if (!error)
{
storage.PutBlob("workerimages", fileName, imageBytes, error);
}
else
{
MessageBox.Show("Error uploading the new image.");
}
}
}
}
Be care using the WriteableBitmap as you may run out of memory if resizing a lot of images. If you only have a few, then pass the size you want saved to the SaveJpeg method. Also make sure you use a value higher than 0 for the quality (last param of SaveJpeg)
var width = wb.PixelWidth/4;
var height = wb.PixelHeight/4;
using (MemoryStream stream = new MemoryStream())
{
wb.SaveJpeg(stream, width, height, 0, 100);
...
...
}
You can also use the JpegRenderer from the Nokia Imaging SDK to resize an image.
var width = wb.PixelWidth/4;
var height = wb.PixelHeight/4;
using (var imageProvider = new StreamImageSource(e.ChosenPhoto))
{
IFilterEffect effect = new FilterEffect(imageProvider);
// Get the resize dimensions
Windows.Foundation.Size desiredSize = new Windows.Foundation.Size(width, height);
using (var renderer = new JpegRenderer(effect))
{
renderer.OutputOption = OutputOption.PreserveAspectRatio;
// set the new size of the image
renderer.Size = desiredSize;
IBuffer buffer = await renderer.RenderAsync();
return buffer;
}
}
I need to retrieve image with webService which converted it into base64
and I need to convert this base64 into BitmapImage and save it into the folder which I added into project
I have these questions:
1) Do I have to convert Base64String into Stream and create a bitmapImage with it?
Can this BAse64 string be used as byte for creating bitmapImage without converting it to Buffer?
2) How to save the bitmapImage in the specific Folder after conversion from Base64 to buffer?
The problem:
no error and no image is saved!
I dont seems to be able to save it. Your help is greatly appreciated.
public async Task Base64StringToBitmapTask(string Base64source,string Filenm)
{
var ims = new InMemoryRandomAccessStream();
var bytes = Convert.FromBase64String(Base64source);
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(bytes);
await dataWriter.StoreAsync();
ims.Seek(0);
var bm = new BitmapImage();
bm.SetSource(ims);
byte[] pixeBuffer = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wb = new WriteableBitmap(bm.PixelWidth,bm.PixelHeight);
await wb.SetSourceAsync(ims);
Stream s1 = wb.PixelBuffer.AsStream();
s1.CopyTo(ms);
pixeBuffer = ms.ToArray();
}
await InsertImageInFolder(pixeBuffer, Filenm);
}
private async Task InsertImageInFolder(byte[] buffer, string filename)
{
IBuffer Ibr = buffer.AsBuffer();
StorageFolder folder = ApplicationData.Current.LocalFolder;
//-1-- Get the folder added into the Project
StorageFolder subfolder = await StorageFolder.GetFolderFromPathAsync("ms-appx:///ProductImages");
//-2---- create a file in this folder
await subfolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
StorageFile sampleFile = await subfolder.GetFileAsync(filename);
await FileIO.WriteBufferAsync(sampleFile, Ibr);
}
I use this code to upload pdf files to sharepoint in my WinForm application. it works. when I click it try to open in sharepoint, I got this
"The document could not be opened for editing. A Windows SharePoint Services compatible application could not be found to edit the document"
If I upload manually, click opens fine.
Here is the code:
FileStream fStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
byte[] bytes = br.ReadBytes((int)numBytes);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/pdf";
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "PUT";
byte[] buffer = new byte[1024];
using (Stream stream = request.GetRequestStream())
using (MemoryStream ms = new MemoryStream(bytes))
for (int i = ms.Read(buffer, 0, buffer.Length); i > 0; i = ms.Read(buffer, 0, buffer.Length))
stream.Write(buffer, 0, i);
WebResponse response = request.GetResponse();
response.Close();
On button click event or on Link button click, I want to download document from sharepoint document library and save it to the user's local disk.
Plz help me on this,If you have any code sample then please share
The problem with outputting a direct link to the file, is that for some content types it may just open in the browser window. If that is not the desired outcome, and you want to force the save file dialog, you'll need to write an ASP/PHP page that you could pass a filename to via the querystring. This page could then read the file and set some headers on the response to indicate that the content-disposition is and attachment.
For ASP.net, if you create a simple aspx page called download.aspx, add the following code into it, then put this file on a server somewhere you can download files by calling this page like this:
http://yourserveraddress/download.aspx?path=http://yoursharepointserver/pathtodoclibrary/file.ext
protected void Page_Load(object sender, EventArgs e)
{
string path = "";
string fileName = "";
path = Request.QueryString["path"];
if (path != null && path.Length > 0)
{
int lastIndex = path.LastIndexOf("/");
fileName = path.Substring(lastIndex + 1, (path.Length - lastIndex - 1));
byte[] data;
data = GetDataFromURL(path);
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(data);
Response.Flush();
}
}
protected byte[] GetDataFromURL(string url)
{
WebRequest request = WebRequest.Create(url);
byte[] result;
byte[] buffer = new byte[4096];
//uncomment this line if you need to be authenticated to get to the files on SP
//request.Credentials = new NetworkCredential("username", "password", "domain");
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (MemoryStream ms = new MemoryStream())
{
int count = 0;
do
{
count = responseStream.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, count);
} while (count != 0);
result = ms.ToArray();
}
}
}
return result;
}
I'd create a LinkButton and set the URL to the document's url programmatically.