PNG file is corrupt when reading back from SQL - sql

I have a database program that stores images to the SQL DB and reads them back to be displayed in a WPF application. if i use Jpeg images it works fine, but if i use PNG images, which i wanted to use to try and keep the transparency ( which disappears anyway when stored ) most of the images come back corrupt.
this is the image that has been selected
i then save it to the db, and add the image the listview
then if i close the application and reload it, it pulls the image back from the db, you can see that it is corrupt in the listview
and then when i select it, the image control also shows the corrupted image
i am storing the image in code using a BitmapImage object, and use this to set the image.source, and also convert this to a byte[] for storing into the image field in the database.
i convert the bitmapimage to a Byte[] with the following line
command.Parameters.AddWithValue("#Image", ImageToByteArray(productImage.ProductImage));
and these are the functions to convert to and from a bitmapimage
private static BitmapImage BuildImage(byte[] image)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
MemoryStream mem = new MemoryStream(image);
bitmap.StreamSource = mem;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
//bitmap.Freeze();
return bitmap;
}
private static byte[] ImageToByteArray(BitmapImage image)
{
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
works fine with Jpegs, but then i have the white background to the images.
any help would be much appreciated.

"JpegBitmapEncoder" is a large clue. Surely you'd want "PNGBitmapEncoder"...?

As personal preference I would change your SQL data column to varbinary(MAX) and use stream and BinaryReader objects to upload the file.
However I think your issue is you are not using PngBitmapEncoder for the PNG you are using the JpegBitmapEncoder irrespective of filetype.
Hope this helps.

Related

How to set Background of a Button without flicker?

I am trying to change the Background of a button to an image source. I want to load that image in memory when we navigate to the page so that it doesn't flicker the first time it shows.
On Windows Phone, I was able to create the image source as such:
StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
BitmapImage bitmapSource = new BitmapImage();
// Avoid flicker by not delay-loading.
bitmapSource.CreateOptions = BitmapCreateOptions.None;
bitmapSource.SetSource(resourceInfo.Stream);
imageSource = bitmapSource;
I tried something similar in my Windows 8 Store app:
BitmapImage bitmapSource = new BitmapImage();
bitmapSource.CreateOptions = BitmapCreateOptions.None;
bitmapSource.UriSource = uri;
imageSource = bitmapSource;
but the same problem occurs. The button already has a different image as the Background, and on a certain event I would like it to change to the new background. But when I change the source, a noticeable flicker is observed. I'm assuming this is because the image is not yet in memory, as the issue goes away the second time the image source is modified.
Anyone know a solution? I need to somehow force the loading of this image.
Thanks!
If you use the SetSourceAsync method on the BitmapImage and await it before you attach it to the image source you should not see the flicker:-
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
imageSource = bitmapImage;
}
The MSDN docs have some more info on this
Thanks Ross, but what I ended up doing instead is I preloaded the half dozen or so bitmaps I needed by using similar code to what you had above, except from resource of course. I did this asynchronously when the page loaded, and then when I set the ImageSource on the button background, I used the already preloaded bitmaps. That way I know I'm not allocated a new chunk of memory for every instance of the bitmap.

Resizing .tif image with imgscalr

I am trying to resize a .tif image and then display it on the browser by converting it to a base64 string. Since ImageIo doesn't support TIF images by default, i have added imageio_alpha-1.1.jar(got it here - http://www.findjar.com/jar/geoserver/jai/jars/jai_imageio-1.1-alpha.jar.html). Now ImageIO is able to register the plugin, which i checked by doing this
String[] writerNames = ImageIO.getWriterFormatNames();
writerNames has TIF in it, this means ImageIO has registered the plugin.
I am resizing the image like this
Map resizeImage(BufferedImage imageData, int width, int height, String imageFormat){
BufferedImage thumbnail = Scalr.resize(imageData, Scalr.Method.SPEED, Scalr.Mode.FIT_EXACT ,
width, height, Scalr.OP_ANTIALIAS);
String[] writerNames = ImageIO.getWriterFormatNames();
ByteArrayOutputStream baos = new ByteArrayOutputStream()
ImageIO.write(thumbnail, imageFormat, baos)
baos.flush()
byte[] imageBytes = baos.toByteArray()
baos.close()
return [imageBytes:imageBytes, imageFormat:imageFormat]
}
String encodeImageToBase64(byte[] imageData){
return Base64.encodeBase64String(imageData)
}
BufferedImage getBufferedImage(byte[] imageData){
ByteArrayInputStream bais = new ByteArrayInputStream(imageData)
BufferedImage bImageFromConvert = ImageIO.read(bais)
bais.close()
return bImageFromConvert
}
String resizeToDimensions(byte[] imageData, String imageFormat, int width, int height){
def bimg = getBufferedImage(imageData)
Map resizedImageData = resizeImage(bimg, width, height, imageFormat)
return encodeImageToBase64(resizedImageData.imageBytes)
}
now i am displaying the image like this
< img src = "data:image/tif;base64,TU0AKgAAAAgADAEAAAMAAA...." /> with this i get failed to load url message(on hovering)
as far as i know the base64 string usually starts with /9j/(may be i am wrong). when i am appending /9j/. I get an error - "image corrupt or truncated". I am not able to figure out the problem here, please help.
At first glance your use of the Data URI format looks correct -- try and narrow down exactly where the failure is.
I would recommend:
In your method where you return the string to the front end, I would recommend printing the entire thing out to the console to get the raw data in Data URI format.
Take the Data URI string, create a sample HTML file with the hard-coded value in it, try and load it... does the image display? If so, great, then your problem is with how you are streaming that back to the front end or how you are trying to load it. (Likely a JavaScript/DOM issue)
If that doesn't work, try and chop the Base64 section out of the example and save it into an example TXT file. In your Java code, load it, decode it and try and create an image out of it and write it back out to a TIFF -- if that didn't work, then there is something wrong with your Base64 handling and the encoding is invalid most likely.
Getting that far should answer most of the questions.
Actually now that I think about it, try and use ImageIO to read the image into a BufferedImage, then process it with imgscalr, then immediately call ImageIO.write and try and write it out to a new TIF someplace else and make sure the ImageIO decoding/encoding process is working correctly.
Hope that helps!

Binary to image in Windows Phone 7

My app retrieves file content from remote server. File can be image or text. When the file is image it returns some string like this:
????\bNExif\0\0MM\0*\0\0\0\b\0\a\0.... and so on. As I understand it's an image but in other format (binary?).
So how can I convert that string to an image and set it to control as source?
Thanks.
I think you can do something like this:
MemoryStream ms = new MemoryStream(bytes);
BitmapImage bi = new BitmapImage();
bi.SetSource(ms);
Then if you have an Image element in XAML, say XamlImage:
XamlImage.Source = bi;

WinJS / WinRT: detect corrupt image file

I'm building a Win8/WinJS app that loads pictures from the local pictures library. Everything is generally working fine for loading valid images and displaying them in a list view.
Now I need to detect corrupt images and disable parts of the app for those images.
For example, open a text file and enter some text in it. Save the file as .jpg, which is obviously not going to be a valid jpg image. My app still loads the file because of the .jpg name, but now I need to disable certain parts of the app because the image is corrupt.
Is there a way I can check to see if a given image that I've loaded is a valid image file? To check if it's corrupt or not?
I'm using standard WinRT / WinJS objects like StorageFile, Windows.Storage.Search related objects, etc, to load up my image list based on searches for file types.
I don't need to filter out corrupt images from the search results. I just need to be able to tell if an image is corrupt after someone selects it in a ListView.
One possible solution would be to check the image's width and height properties to determine whether it is valid or not.
Yeah, the contentType property will return whatever the file extension is. The best way I can find it to look at the image properties:
file.properties.getImagePropertiesAsync()
.done(function(imageProps) {
if(imageProps.width === 0 && imageProps.height === 0) {
// I'm probably? likely? invalid.
});
where SelectImagePlaceholder is an Image Control.. =)
StorageFile file;
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
try
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
SelectImagePlaceholder.Source = bitmapImage;
//SelectImagePlaceholder.HorizontalAlignment = HorizontalAlignment.Center;
//SelectImagePlaceholder.Stretch = Stretch.None;
this.SelectImagePlaceholder.DataContext = file;
_curMedia = file;
}
catch (Exception ex)
{
//code Handle the corrupted or invalid image
}
}

Displaying Tiff files in SSRS reports

I have a requirement to be be able to embed scanned tiff images into some SSRS reports.
When I design a report in VS2005 and add an image control the tiff image displays perfectly however when I build it. I get the warning :
Warning 2 [rsInvalidMIMEType] The value of the MIMEType property for the image ‘image1’ is “image/tiff”, which is not a valid MIMEType. c:\SSRSStuff\TestReport.rdl 0 0
and instead of an image I get the little red x.
Has anybody overcome this issue?
Assuming you're delivering the image file via IIS, use an ASP.NET page to change image formats and mime type to something that you can use.
Response.ContentType = "image/png";
Response.Clear();
using (Bitmap bmp = new Bitmap(tifFilepath))
bmp.Save(Response.OutputStream, ImageFormat.Png);
Response.End();
I have been goggling fora solution on how to display a TIFF image in a SSRS report but I couldn't find any and since SSRS doesn's support TIFF, I thought converting the TIFF to one of the suppported format will do the trick. And it did. I don't know if there are similar implementation like this out there, but I am just posting so others could benefit as well.
Note this only applies if you have a TIFF image saved on database.
Public Shared Function ToImage(ByVal imageBytes As Byte()) As Byte()
Dim ms As System.IO.MemoryStream = New System.IO.MemoryStream(imageBytes)
Dim os As System.IO.MemoryStream = New System.IO.MemoryStream()
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(ms)
img.Save(os, System.Drawing.Imaging.ImageFormat.Jpeg)
Return os.ToArray()
End Function
Here’s how you can use the code:
1. In the Report Properties, Select Refereneces, click add and browse System.Drawing, Version=2.0.0.0
2. Select the Code Property, Copy paste the function above
3. Click Ok
4. Drop an Image control from the toolbox
4.1. Right-Click the image and select Image Properties
4.2. Set the Image Source to Database
4.3. In the Use this field, Click expression and paste the code below
=Code.ToImage(Fields!FormImage.Value)
4.4. Set the appropriate Mime to Jpeg
Regards,
Fulbert
Thanks Peter your code didn't compile but the idea was sound.
Here is my attempt that works for me.
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "image/jpeg";
Response.Clear();
Bitmap bmp = new Bitmap(tifFileLocation);
bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
Response.End();
}