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;
}
}
Related
I've got an ASP.NET core application that uploads images to Azure. I am attempting to resize an image using Magick.NET before uploading said image to Azure Blob container. So far, I've managed to save the image to a folder in a local hard drive. Is this the correct way of writing this?
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Product products)
{
var files = products.UploudThumbnail;
List<string> image = new List<string>();
List<string> names = new List<string>();
if (files != null)
{
foreach (var file in files)
{
if (ModelState.IsValid)
{
if (file.ContentType == "image/jpeg" || file.ContentType == "image/jpg")
{
if (file.Length < 1 * 1000 * 1000)
{
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
var fileName = parsedContentDisposition.FileName.Trim('"');
names.Add(fileName);
fileName = Guid.NewGuid().ToString() + "-" + fileName;
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
cloudBlockBlob.Properties.ContentType = file.ContentType;
await cloudBlockBlob.UploadFromStreamAsync(file.OpenReadStream());
image.Add(cloudBlockBlob.Uri.AbsoluteUri);
const int size = 20;
const int quality = 75;
using (var image = new MagickImage(file.OpenReadStream()))
{
image.Resize(size, size);
image.Strip();
image.Quality = quality;
//how to save it into azure?
image.Write(fileName);
}
}
else
{
ModelState.AddModelError("UploudThumbnail", "Max size not accepted");
}
}
else
{
ModelState.AddModelError("UploudThumbnail", "jpeg & jpg are accepted");
}
}
}
}
_context.Add(products);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
Just write the image to a memory stream and upload it using the UploadFromStreamAsync method.
Example (pseudo):
using (var memStream = new MemoryStream())
{
image.Write(memStream);
memStream.Seek(0, SeekOrigin.Begin);
await cloudBlockBlob.UploadFromStreamAsync(memStream);
}
I need to display the images from remote database.here I have a code to display images from local file.But I can't get it from remote server
C# code
DispatcherTimer timer = new DispatcherTimer();
List<string> files = new List<string>() { "http://technomindtech.com/1tele-pixel.com/ad/banner.jpg", "http://technomindtech.com/1tele-pixel.com/ad/logo_banner.jpg", "http://technomindtech.com/1tele-pixel.com/ad/images.jpeg" };
List<BitmapImage> images = new List<BitmapImage>();
int current = 0;
foreach (string file in files)
{
BitmapImage image = new BitmapImage(new Uri(file, UriKind.Relative));
images.Add(image);
}
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(3);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
void timer_Tick(object sender, EventArgs e)
{
Image1.Source = images[current];
current++;
if (current >= files.Count)
current = 0;
}
Xaml code
<Image x:Name="Image1" Stretch="Fill" Width="410" Grid.ColumnSpan="3" Margin="-8,0,-29,0" />
but it throws Uri exception it can't show the image
In your foreach block, when creating an image from the Uri, you are stating that the path is relative, but it is actually absolute. So, modifying the statement should work:
BitmapImage image = new BitmapImage(new Uri(file, UriKind.Absolute));
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();
Please can you help me with me threading. I'm trying to download a file and at the same time update a BTProgressHUD progress display. I know that the reason that it's not working is to do with the download using the main thread and not allowing me to update the UI but I can't work out how to correctly use the thread pool to allow me to update the BTProgressHUD whilst the file is downloading. Please help!!
`
BTProgressHUD.Show("Downloading...", progress);
string this_file = "example.pdf";
string file_url = "http://our_server.com/files/" + this_file;
Uri url = new Uri(file_url);
var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var folder = Path.Combine (documents, "", "PDF");
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
Int64 iSize = response.ContentLength;
// keeps track of the total bytes downloaded so we can update the progress bar
Int64 iRunningByteTotal = 0;
// use the webclient object to download the file
using (System.Net.WebClient client = new System.Net.WebClient())
{
// open the file at the remote URL for reading
using (System.IO.Stream streamRemote = client.OpenRead(new Uri(file_url)))
{
// using the FileStream object, we can write the downloaded bytes to the file system
using (Stream streamLocal = new FileStream(folder + "/" + this_file, FileMode.Create, FileAccess.Write, FileShare.None))
{
// loop the stream and get the file into the byte buffer
int iByteSize = 0;
byte[] byteBuffer = new byte[iSize];
while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
// write the bytes to the file system at the file path specified
streamLocal.Write(byteBuffer, 0, iByteSize);
iRunningByteTotal += iByteSize;
// calculate the progress out of a base "100"
double dIndex = (double)(iRunningByteTotal);
double dTotal = (double)byteBuffer.Length;
double dProgressPercentage = (dIndex / dTotal);
int iProgressPercentage = (int)(dProgressPercentage * 100);
if (iProgressPercentage == 100)
{
var z = new UIAlertView ("Download Complete", this_file + " downloaded.", null, "OK", null);
z.Show();
BTProgressHUD.Dismiss();
}
if (iProgressPercentage % 10 == 0)
{
// THIS BUT NEVER HAPPENS!!! Cannot update the progress display
progress += 0.1f;
BTProgressHUD.Show("XXX", progress);
}
} // while..
streamLocal.Close(); // clean up the file stream
} // using stream
streamRemote.Close(); // close the connection to the remote server
} // using I.O
} // using system.net
`
Any help would be very very much appreciated.
I have used the TPL to kick of a background thread then called back to the UI by using InvokeOnMainThread. I have substituted the BTProgressHUD for a UILabel but it should work the same. Here is it working:
private void DownloadCoffeePDF()
{
Task.Factory.StartNew (() => {
InvokeOnMainThread(() => {
this.TheLabel.Text = string.Format("Downloading...{0}", progress);
});
string file_url = "http://www.pnf.org/coffeeedited041001.pdf";
Uri url = new Uri(file_url);
var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var folder = Path.Combine (documents, "", "PDF");
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
Int64 iSize = response.ContentLength;
// keeps track of the total bytes downloaded so we can update the progress bar
Int64 iRunningByteTotal = 0;
// use the webclient object to download the file
using (System.Net.WebClient client = new System.Net.WebClient())
{
// open the file at the remote URL for reading
using (System.IO.Stream streamRemote = client.OpenRead(new Uri(file_url)))
{
// using the FileStream object, we can write the downloaded bytes to the file system
using (Stream streamLocal = new FileStream(folder + "/" + "Coffee.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
// loop the stream and get the file into the byte buffer
int iByteSize = 0;
byte[] byteBuffer = new byte[iSize];
while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
// write the bytes to the file system at the file path specified
streamLocal.Write(byteBuffer, 0, iByteSize);
iRunningByteTotal += iByteSize;
// calculate the progress out of a base "100"
double dIndex = (double)(iRunningByteTotal);
double dTotal = (double)byteBuffer.Length;
double dProgressPercentage = (dIndex / dTotal);
int iProgressPercentage = (int)(dProgressPercentage * 100);
if (iProgressPercentage == 100)
{
InvokeOnMainThread(() => {
var z = new UIAlertView ("Download Complete", "Coffee.pdf" + " downloaded.", null, "OK", null);
z.Show();
this.TheLabel.Text = "Download Complete";
});
}
if (iProgressPercentage % 10 == 0)
{
InvokeOnMainThread(() => {
// THIS BUT NEVER HAPPENS!!! Cannot update the progress display
progress += 0.1f;
this.TheLabel.Text = string.Format("{0}", progress);
});
}
} // while..
streamLocal.Close(); // clean up the file stream
} // using stream
streamRemote.Close(); // close the connection to the remote server
} // using I.O
} // using system.net
});
}
Working on one windows application (.Net 4.0) which will accept font file name as input and will return images for each glyph in font. Tried all possible Google stuff but not getting all glyph s images. And if getting images that also have some wrong out put. Please suggest me the ways to do this... Currently had following work out...
private void generateBitmaps(string strFontpath)
{
////Generate font object
GlyphTypeface font = new GlyphTypeface(new Uri(strFontpath));
int fontSize = 22;
int intGlyphcount = 0;
//Collect geometry of all glyphs
var Glyphs = from glyphIndex in font.CharacterToGlyphMap.Values
select font.GetGlyphOutline(glyphIndex, fontSize, 1d);
// now create the visual we'll draw them to
DrawingVisual viz = new DrawingVisual();
System.Drawing.Size cellSize = new System.Drawing.Size(fontSize, Convert.ToInt32(fontSize * font.Height));
int bitWidth = (int)Math.Ceiling(Convert.ToDecimal(cellSize.Width*10));
int bitHeight = (int)Math.Ceiling(Convert.ToDecimal(cellSize.Height * 10));
//using (DrawingContext dc = viz.RenderOpen())
{
foreach (var g in Glyphs)
{
if (intGlyphcount > font.GlyphCount)
break;
//if (g.IsEmpty())
// continue; // don't draw the blank ones
DrawingContext dc = viz.RenderOpen();
dc.PushTransform(new TranslateTransform());
System.Windows.Media.Pen glyphPen = new System.Windows.Media.Pen(System.Windows.Media.Brushes.Black, 1);
dc.DrawGeometry(System.Windows.Media.Brushes.Red, glyphPen, g);
//GeometryDrawing glyphDrawing = new GeometryDrawing(System.Windows.Media.Brushes.White, glyphPen, g);
//DrawingImage geometryImage = new DrawingImage(glyphDrawing);
//dc.DrawImage(geometryImage, new Rect(0, 0, 150, 150));
dc.Close();
//geometryImage.Freeze();
//dc.Pop(); // get rid of the transform
RenderTargetBitmap bmp = new RenderTargetBitmap(
200, 200,
96, 96,
PixelFormats.Pbgra32);
bmp.Render(viz);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
using (FileStream file = new FileStream(#"GlyphList\Glyph" + intGlyphcount++ + ".png", FileMode.Create))
encoder.Save(file);
//dc.Pop();
}
}
MessageBox.Show("Done");
}
If You got glyph in font as image use external dll
This dll is available in url
http://www.gnostice.com/XtremeFontEngine_dot_NET.asp