Resize Image with PHP for using in .NET - c#

i have images on a webserver and I convert they in Base64 to receive it on a .Net application. I use this code:
$imagedata = file_get_contents($local_uri);
$d = base64_encode($imagedata);
It works perfekt.
Now i had the idea to resize the images to save time for transmission.
So I resize the images with a simple PHP-Framework from http://deruwe.de/vorschaubilder-einfach-mit-php-realisieren-teil-2.html
On behind it use ImageJPEG to "return" or create the edited image.
On an other post here i read that if you want to use ImageJPEG and translate it on Base64 you have to use this code:
ob_start();
$thumbnail->output(false, false);
$p = ob_get_contents();
ob_end_clean();
$d = base64_encode($p);
The "new" Base64 code seems legit, because if I try to illustrate it with http://www.freeformatter.com/base64-encoder.html, I got a legit image.
BUT due an unknown reason my .Net application will throw an System.NotSupportedException (No imaging component suitable to complete this operation was found.) and don't like the "new" one.
This is my .Net function to convert Base64 String in BitmapImage:
public static BitmapImage getImage(String s)
{
byte[] binaryData = Convert.FromBase64String(s);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = new MemoryStream(binaryData);
bi.EndInit();
return bi;
}
Any idea whats gone wrong or how to fix it?

Related

How to convert stream to bitmap in xamarin.forms to adjust image contrast

I am trying to raise the contrast of an image in Xamarin.forms using this algorithm. My code gives me in image in the form of a System.IO.Stream, which I want to convert to a Bitmap/LockBitmap to use the algorithm.
I tried code such as using System.Drawing, which didn't work. The error said "the type or namespace bitmap could not be found." Then, I tried using Android.Graphics, which fixes that error, but I don't know if it will work with a Xamarin.forms app that needs to run on Android and iOS.
Even if that does work, how do I actually convert a System.IO.Stream into a Bitmap? Is there another algorithm that doesn't require bitmaps?
Edit: I think I can use BitmapFactory to convert the stream into a bitmap.
you could use DependencyService to convert System.IO.Stream into Bitmap ,after raise the contrast of an image ,return the new stream,and show the Image in forms page.
like:
create a interface IRaiseImage.cs:
public interface IRaiseImage
{
Stream RaiseImage(Stream stream);
}
then in Droid.project,creat AndroidRaiseImage.cs:
[assembly: Dependency(typeof(AndroidRaiseImage))]
namespace App18.Droid
{
class AndroidRaiseImage : IRaiseImage
{
public Stream RaiseImage(Stream stream)
{
Bitmap bitmap = BitmapFactory.DecodeStream(stream);
//raise the bitmap contrast
...
// return the new stream
MemoryStream ms = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Png, 100, ms);
return ms;
}
}
}
then you could set to the Image in your forms page:
MemoryStream memoryStream = new MemoryStream();//your original image stream
Image image = new Image();
image.Source = ImageSource.FromStream(() => DependencyService.Get<IRaiseImage>().RaiseImage(memoryStream));

Metro APP - BitmapImage to Byte[] or Download Image from Web and convert it to a Byte[] Array

Is there a way to convert a BitmapImage (Windows.UI.Xaml.Media.BitmapImage) to an Byte[] Array? Nothing I've tried work....
Another possible scenario (if BitmapImage cannot be converted to Byte array) is to download the image from web and then convert it to an array...
But I don't know how I can do that...
It would be really nice, if someone have an idea.
Current try:
HttpClient http = new HttpClient();
Stream resp = await http.GetStreamAsync("http://localhost/img/test.jpg");
var ras = new InMemoryRandomAccessStream();
await resp.CopyToAsync(ras.AsStreamForWrite());
BitmapImage bi = new BitmapImage();
bi.SetSource(ras);
byte[] pixeBuffer = null;
using (MemoryStream ms = new MemoryStream())
{
int i = bi.PixelHeight;
int i2 = bi.PixelWidth;
WriteableBitmap wb = new WriteableBitmap(bi.PixelWidth, bi.PixelHeight);
Stream s1 = wb.PixelBuffer.AsStream();
s1.CopyTo(ms);
pixeBuffer = ms.ToArray();
}
But it doesn't work... i & i2 are always set to 0. So ras doesn't work correctly.... What's going on?
Thanks
In your code you're never waiting for the BitmapImage to load the image from the web, so it does not know its PixelWidth/PixelHeight when you access them. You could wait for it to load - for example using the AsyncUI library by calling "await bi.WaitForLoadedAsync()". This would not really help you here if you want to access the decoded pixels since BitmapImage does not give you access to the pixels and there is currently no API to convert a BitmapImage into a WriteableBitmap.
You can check an earlier question about the topic. You would need to get the image file from the web with something like HttpClient.GetAsync(), then load it using something like BitmapDecoder.

Displaying image in ASP.NET C#

I am converting Base64 code to image and I am using following way to save and display that image.
var kpin = Base64ToImage(TextBox1.Text);
kpin.Save(#"e:\myim.png");
Image1.ImageUrl = #"e:\myim.png";
and class is
public Image Base64ToImage(string base64String)
{
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
and this process working fine but I need an image not to be saved in hard disk. How to display this image directly without saving to hard disk and retrieving back.
Instead of setting the Image1.ImageURL to the path of your image, you can instead do one of several things:
Use an img tag with the Base64 data in it directly - http://www.sweeting.org/mark/blog/2005/07/12/base64-encoded-images-embedded-in-html
Not all browsers support this.
Create an Action or Webform (depending on whether you're using ASP.NET MVC or not) that takes as input whatever you need to either retrieve or generate the Base64 encoded data, and then set the response headers to serve the correct content type (image/png or something) and write the image directly to the Response.OutputStream (or use ContentResult in ASP.NET MVC). Tons of examples via Stackoverflow on how to do either.
-M
Don't bother with the image object at all, and just do it direct:
public void Base64ToResponse(string base64String)
{
Response.ContentType = "text/png"; //or whatever...
byte[] imageBytes = Convert.FromBase64String(base64String);
Response.OutputStream(imageBytes, 0, imageBytes.Length);
}

Converting varbinary to image in silverlight (part 2)

I am trying to convert a varbinary to an image in my silverlight project.
First I get the Binary from my database in my service.
[OperationContract]
public byte[] getAfbeelding(int id)
{
var query = (from p in dc.Afbeeldings
where p.id == id
select p.source).Single();
byte[] source = query.ToArray();
Then I try to convert the varbinary to an image, using code found on StackOverflow:
public static string convertToImage(byte[] source)
{
MemoryStream ms = new MemoryStream(source);
Image img = Image.FromStream(ms);
return img.Source.ToString();
}
But as it turns out, the silverlight Image does not have a .FromStream, I tried all the examples found in this thread but NONE of them work in silverlight.
'System.Windows.Controls.Image' does not contain a definition for 'FromStream'
So yeah, I'm kinda lost and am not sure what to do.
Any ideas on how to do this in silverlight?
You're almost right. The following code should be all you need:
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(new MemoryStream(imageData));
newImage.Source = bitmapImage;
where imageData is of type byte[] and newImage is the image you want to update.
you sould have a look at WriteableBitmap.
there is a pretty nice set of extensions freely available on codepelex or Nuget

OutOfMemory exception when loading an image in .Net

Im loading an image from a SQL CE db and then trying to load that into a PictureBox.
I am saving the image like this:
if (ofd.ShowDialog() == DialogResult.OK)
{
picArtwork.ImageLocation = ofd.FileName;
using (System.IO.FileStream fs = new System.IO.FileStream(ofd.FileName, System.IO.FileMode.Open))
{
byte[] imageAsBytes = new byte[fs.Length];
fs.Read(imageAsBytes, 0, imageAsBytes.Length);
thisItem.Artwork = imageAsBytes;
fs.Close();
}
}
and then saving to the Db using LINQ To SQL.
I load the image back like so:
using (FileStream fs = new FileStream(#"C:\Temp\img.jpg", FileMode.CreateNew ,FileAccess.Write ))
{
byte[] img = (byte[])encoding.GetBytes(ThisFilm.Artwork.ToString());
fs.Write(img, 0, img.Length);
}
but am getting an OutOfMemoryException. I have read that this is a slight red herring and that there is probably something wrong with the filetype, but i cant figure what.
Any ideas?
Thanks
picArtwork.Image = System.Drawing.Bitmap.FromFile(#"C:\Temp\img.jpg");
Based on the code you provided it seems like you are treating the image as a string, it might be that data is being lost with the conversion from byte[] to string and string to byte[].
I am not familiar with SQL CE, but if you can you should consider treating the data as a byte[] and not encoding to and from string.
I base my assumption in this line of code
byte[] img = (byte[])encoding.GetBytes(ThisFilm.Artwork.ToString());
The GDI has the bad behavior of throwing an OOM exception whenever it is not capable of understanding a certain image format. Use Irfanview to see what kind of image that really is, it is likely GDI can't handle it.
My advice would be to not use a FileStream to load images unless you need access to the raw bytes. Instead, use the static methods provided in Bitmap or Image objects:
Image img = Image.FromFile(#"c:\temp\img.jpg")
Bitmap bmp = Bitmap.FromFile(#"c:\temp\img.jpg")
To save the file use .Save method of the Image or Bitmap object:
img.Save(#"c:\temp\img.jpg")
bmp.Save(#"c:\temp\img.jpg")
Of course we don't know what type ArtWork is. Would you care to share that information with us?

Categories