I am working on a project which requires to stored the 32x32 size Icons(png) in table. I am storing the image in table, but when I am getting it to display on page it feels something distorted. These are the png images so somewhere it could be transparent. But when I am showing that image in list of asp.Net page the transparent spaces are filled with black color.
Are there any ways/methods to store the png image in the table without distorting it's quality.
Thanks
This happens when you save Image to byte array with wrong ImageFormat. Use this code:
public byte[] imageToByteArray(string imagePath)
{
return imageToByteArray(System.Drawing.Image.FromFile(imagePath));
}
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
byte[] result = null;
using (MemoryStream ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
result = ms.ToArray();
}
return result;
}
Related
I have a WEB-APP that is a Web-Cam App that takes images and stores into a database as bytes, Now with that being said I also don't want to save the images those are taken and save it in any kind of folder right now the only way to show the image that is captured for me to save it and view it again to do that I have a input stream that's fired when the capture image is clicked.
using (StreamReader reader = new StreamReader(Request.InputStream))
{
hexString = Server.UrlEncode(reader.ReadLine());
string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
string imagePath = string.Format("~/Pictures/{0}.png", imageName);
File.WriteAllBytes(Server.MapPath(imagePath), ConvertHexToBytes(hexString));
Session["Byte"] = hexString;
// Session["CapturedImage"] = ResolveUrl(imagePath);
Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(ConvertHexToBytes(hexString));
}
I have a method that converts that hex string to bytes:
private static byte[] ConvertHexToBytes(string hex)
{
// MemoryStream stream = new MemoryStream();
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
I want to Display that image using the bytes, I don't want to save the image in any folder. How do I take those bytes and put them into a image?
I have a slandered image tag Image1.imageUrl =? I tried the base64 version but it doesn't work.
How do I take those bytes and put them into a image?
Note: I am making the assumption as per your question that your question is not about converting hex to bytes.
Imagine you have this in your aspx page:
<asp:Image ID="Image1" runat="server" />
In the code below GetImageBytes returns a byte[]. Then, to serve the image (without saving it to a file), all we need to do is this:
using (MemoryStream ms = new MemoryStream(GetImageBytes()))
{
// Image1 is instance of System.Web.UI.WebControls
this.Image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
}
private byte[] GetImageBytes()
{
return System.IO.File.ReadAllBytes(Server.MapPath("~/Content/someImage.jpg"));
}
Try that out by placing an image in your Content folder to test it out. Now that you know it works, you need to make sure it can work with your ConvertHexToBytes method. If it does not, then clearly something is wrong with ConvertHexToBytes method.
I am trying to understand and implement a piece of code for Tiff compression.
I have already used 2 separate techniques - Using 3rd party dll's LibTiff.NEt (1st method is bulky) and the Image save method, http://msdn.microsoft.com/en-us/library/ytz20d80%28v=vs.110%29.aspx (2nd method works only on windows 7 machine but not on windows 2003 or 2008 server).
Now I am looking to explore this 3rd method.
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using System.Drawing.Imaging;
int width = 800;
int height = 1000;
int stride = width/8;
byte[] pixels = new byte[height*stride];
// Try creating a new image with a custom palette.
List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
colors.Add(System.Windows.Media.Colors.Red);
colors.Add(System.Windows.Media.Colors.Blue);
colors.Add(System.Windows.Media.Colors.Green);
BitmapPalette myPalette = new BitmapPalette(colors);
// Creates a new empty image with the pre-defined palette
BitmapSource image = BitmapSource.Create(
width,
height,
96,
96,
System.Windows.Media.PixelFormats.BlackWhite,
myPalette,
pixels,
stride);
FileStream stream = new FileStream(Original_File, FileMode.Create);
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Compression = TiffCompressOption.Ccitt4;
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(stream);
But I don't have a full understanding of what is happening here.
There is obviously some kind of a memory stream that the compression technique is being applied to. But I am a bit confused how to apply this to my specific case. I have an original tiff file, I want to use this method to set its compression to CCITT and save it back. Can anyone help?
I copied the above code and the code runs. But my end output file is a solid black background image. Although on the positive side it is of the correct compression type.
http://msdn.microsoft.com/en-us/library/ms616002%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.tiffcompressoption%28v=vs.100%29.aspx
http://social.msdn.microsoft.com/Forums/vstudio/en-US/1585c562-f7a9-4cfd-9674-6855ffaa8653/parameter-is-not-valid-for-compressionccitt4-on-windows-server-2003-and-2008?forum=netfxbcl
LibTiff.net is a little bulky because it's based off LibTiff, which has its own set of problems.
My company (Atalasoft) has the ability to do that fairly easily, and the free version of the SDK will do the task you want with a few restrictions. The code for re-encoding a file would look like this:
public bool ReencodeFile(string path)
{
AtalaImage image = new AtalaImage(path);
if (image.PixelFormat == PixelFormat.Pixel1bppIndexed)
{
TiffEncoder encoder = new TiffEncoder();
encoder.Compression = TiffCompression.Group4FaxEncoding;
image.Save(path, encoder, null); // destroys the original - use carefully
return true;
}
return false;
}
Things you should be aware of:
this code will only work properly on 1bpp images
this code will NOT work properly on multi-page TIFFs
this code does NOT preserve metadata within the original file
and I would want the code to at least check for that. If you are inclined to have a solution that better preserves what's in the content of the file, you would want to do this:
public bool ReencodeFile(string origPath, string outputPath)
{
if (origPath == outputPath) throw new ArgumentException("outputPath needs to be different from input path.");
TiffDocument doc = new TiffDocuemnt(origPath);
bool needsReencoding = false;
for (int i=0; i < doc.Pages; i++) {
if (doc.Pages[i].PixelFormat == PixelFormat.Pixel1bppIndexed) {
doc.Pages[i] = new TiffPage(new AtalaImage(origPath, i, null), TiffCompression.Group4FaxEncoding);
needsReencoding = true;
}
}
if (needsReendcoding)
doc.Save(outputPath);
return needsReencoding;
}
This solution will respect all pages within the document as well as document metadata.
I am making a small application in android that browse image from the gallery or take a picture from the camera. Then the selected image is compressed and uploaded to the server. I had compressed the image using Base64 String in android and for uploading image i am making a web service in ASP.NET. But i'm not sure how to decode the string(converted using Base64 in android) into image(the web service should be able to convert it). Please help me.
Thanks in advance
You can convert base64string to image by Image.FromStream. You will need to convert the base64string to stream first.
byte[] imageBytes = Convert.FromBase64String(imgBase64String);
Image img = null;
using (MemoryStream ms1 = new MemoryStream(imageBytes))
{
img = Image.FromStream(ms1);
}
if (img != null)
{
// ...
}
I have images in the database (SQlServer 2008 R2) in a varbinary column. My report is developed in ASP.net 3.5 in Visual Studio 2010. On my report in a table, I use an Image, set the MIME type to image/jpeg, image source as Database & the image is displayed correctly in the report. Everything works!! Now my issue is that, I would like to add a hyperlink to that image so that when the user clicks on the image it opens in another window/tab in its original format. This will help the user to get a closer look at the image.
I tried to add Hyperlink - Go to URL - Expression
="http://localhost:49170/MtkMobileDeposit_FailedTransaction/Account/ReportByUserName.aspx?BackImageOriginal=" & Fields!BackImageOriginal.Value
But I cannot get it to display only the image. Instead it displays the entire report in a new tab. How do I first get the URL for the images to work ? Please help.
Thanks,
sdd
Your best bet is to use a httphandler to process your request.
Create an ImageHandler.ashx that will take in the record id. Then you can get the image's byte array and out put it to the screen.
Your new URL will look like
"/ImageHandler.ashx?Record_ID=" & Fields!RecordId.Value
public class ImageHandler : IHttpHandler
{
public int Record_ID
{
get { return Convert.ToInt32(HttpContext.Current.Request.QueryString["Record_ID"]); }
}
public void ProcessRequest(HttpContext context)
{
// get image from database into a byte array
Component.ImageController objImageController = new Component.ImageController();
Component.ImageInfo objImageInfo = objImageController.getImage(Record_ID);
byte[] byteArray = objImageInfo.photo;
// output it to the screen
context.Response.Clear();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(byteArray);
context.ApplicationInstance.CompleteRequest();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Hi:
IN my application,I have some images saved in the db,so I create a ImgDownLoad.aspx to retrive the image and retun them,since the image in the db may very large(some of them is more than 20M),so I generate some thumbnails ,this is the code:
page_load(){
string id=Requset.QueryString["id"];
string imgtype=Requset.Querystring["itype"];
if(imgType=="small")
{
//request the thumbnail
string small_loaction=getSmallLocationById(id);
if(!File.exists(small_location)
{
byte[] img_stream =getStreamFromDb(id);
Image img=Image.frameStream(new MemsorStream(img_steam));//here,I often get the out of memory error,but I am not sure when it will happen.
generateSmallImage(img,location)
}
Response.TransferFile(small_location);
}
else if(imgType=="large"){
byte[] img_stream =getStreamFromDb(id);
new MemorySteam(img_stream).writeTo(Response.outputstream);
}
}
Anything wrong?
ALso,since I do not know the image format,so I can not add the
Response.contenttype="image/xxx";
What confusing me most is that I will meet the out of memory error,so I change the code:
try{
byte[] img_stream =getStreamFromDb(id);
Image img=Image.frameStream(new MemsorStream(img_steam));//here,I often get the out of memory error,but I am not sure when it will happen.
generateSmallImage(img,location)
}
catche(exceptin e){
//the small image can not generated,just return the whole image
new MemorySteam(img_stream).writeTo(Response.outputstream);
return;
}
In this case,I will avoid the out of memory problem,but some large image can not downloaded sometime.
So I wonder if there are any ways to handle the large image stream?
Take a large image for exmaple:
resolution:12590x4000
size:26M.
In fact,I have opened a large image(almost 24M) with the mspaint,and then save the image again,I found that it size is much smaller than at first. So is it possible to resize the image in the server side? Or other good manners to hanle my problem?
Firstly, you're not disposing of the Image and Stream type instances that you create - given subsequent calls, over time, this is bound to cause issues; particularly with images around the 20meg mark!
Also, why create the thumbnails every call? Create once and cache, or flush to disk: either way, serve a 'one you made earlier' rather than do this processing over and over.
I would recommend, however, you try an minimise the size (in bytes) of the images. Some might argue that they shouldn't be in the database if over 1meg, but store them on disk and a file name in the database. I guess that's open for debate, browse if interested.
To your comment, I'd urge you not to allow other scopes take control of resources 'owned' by another; dispose of items in the scope that creates them (obviously sometimes some things need to stick around, but what is responsible for them should be clear). Here's a little rework of some of your code:
if (imgType == "small")
{
string small_loaction = getSmallLocationById(id);
if(!File.exists(small_location)
{
byte[] imageBytes = getStreamFromDb(id);
using (var imageStream = new MemoryStream(imageBytes))
{
using (var image = Image.FromStream(imageStream))
{
generateSmallImage(image, small_location)
}
}
}
Response.TransferFile(small_location);
}
else if (imgType=="large")
{
byte[] imageBytes = getStreamFromDb(id);
Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
}