Excel image in a cell - c#

How do I insert an image (of type Image) into a specific cell in a Excel sheet
taperSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item("Taper");
Microsoft.Office.Interop.Excel.Range cell = GetMyPictureCELL(taperSheet);
Image myImage = new Image();
RenderTargetBitmap bmp;
bmp = new RenderTargetBitmap((int)this.Width, (int)this.Height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(myViewPort);
myImage.Source = bmp;
myImage.Stretch = Stretch.Uniform;
and now ?
I was hoping for
cell.Add(myImage)
But I assume it is not that easy.
/Stefan
Thanks for your input doitgood
The following code works for me
In my case my Image source is a viewport (myViewPort)
The placement of the image is determinated by cell
try
{
Image myImage = new Image();
RenderTargetBitmap bmp;
PngBitmapEncoder encoder;
string fileName;
System.IO.Stream stream;
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Picture pic = null;
Microsoft.Office.Interop.Excel.Pictures p = null;
bmp = new RenderTargetBitmap((int)this.Width, (int)this.Height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(myViewPort);
myImage.Source = bmp;
myImage.Stretch = Stretch.Uniform;
fileName = System.IO.Path.GetTempFileName();
stream = System.IO.File.OpenWrite(fileName);
encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
encoder.Save(stream);
stream.Close();
p = taperSheet.Pictures(missing) as Microsoft.Office.Interop.Excel.Pictures;
pic = p.Insert(fileName, missing);
pic.Left = cell.Left;
pic.Top = cell.Top;
}
catch { }

Try this:
object missing = System.Reflection.Missing.Value;
Excel.Range picPosition = GetPicturePosition(); // retrieve the range for picture insert
Excel.Pictures p = yourWorksheet.Pictures(missing) as Excel.Pictures;
Excel.Picture pic = null;
pic = p.Insert(yourImageFilePath, missing);
pic.Left = Convert.ToDouble(picPosition .Left);
pic.Top = Convert.ToDouble(picPosition .Top);
pic.Placement = // Can be any of Excel.XlPlacement.XYZ value
And don't forget to release all that stuff!

Or Try this:
private void PlacePicture(Image picture, Range destination)
{
Worksheet ws = destination.Worksheet;
Clipboard.SetImage(picture);
ws.Paste(destination, false);
Pictures p = ws.Pictures(System.Reflection.Missing.Value) as Pictures;
Picture pic = p.Item(p.Count) as Picture;
ScalePicture(pic, (double)destination.Width, (double)destination.Height);
}
private void ScalePicture(Picture pic, double width, double height)
{
double fX = width / pic.Width;
double fY = height / pic.Height;
double oldH = pic.Height;
if (fX < fY)
{
pic.Width *= fX;
if (pic.Height == oldH) // no change if aspect ratio is locked
pic.Height *= fX;
pic.Top += (height - pic.Height) / 2;
}
else
{
pic.Width *= fY;
if (pic.Height == oldH) // no change if aspect ratio is locked
pic.Height *= fY;
pic.Left += (width - pic.Width) / 2;
}
}

Related

Final image has smaller image after merging multiple images

I am trying to create a big final jpg image from 4 different jpg images. I noticed after adding images onto the final image, the size of the image changes.
The size of the image should remain the same on the final image too.
Ex- The galaxy image(dark sky) on the final image looks small, compared to the actual image.
Any help would be appreciated.
private void CombineImages()
{
string path1 = #"C:\temp\";
DirectoryInfo directory = new DirectoryInfo(path1);
//change the location to store the final image.
FileInfo[] files = directory.GetFiles();
string finalImage = #"C:\\images\\FinalImage3.jpg";
List<int> imageHeights = new List<int>();
List<int> imagewidths = new List<int>();
int nIndex = 0;
int width = 0;
int maxHeight = 0;
int totalHeight = 0;
bool odd = true;
bool firstRow = true;
//to get height and width to create final image
foreach (FileInfo file in files)
{
if (odd)
{
if (firstRow)
{
Image img = Image.FromFile(file.FullName);
firstRow = false;
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
odd = false;
}
else
{
Image img = Image.FromFile(file.FullName);
maxHeight = imageHeights.Max();
imagewidths.Add(width+100);
width = 0;
totalHeight = totalHeight + maxHeight+img.Height+100;
imageHeights.Clear();
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
odd = false;
}
}
else
{
Image img = Image.FromFile(file.FullName);
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
odd = true;
}
}
imageHeights.Sort();
Bitmap img3 = new Bitmap(imagewidths.Max(), totalHeight);
Graphics g = Graphics.FromImage(img3);
g.Clear(Color.Gainsboro);
imageHeights = new List<int>();
imagewidths = new List<int>();
nIndex = 0;
width = 0;
maxHeight = 0;
totalHeight = 0;
odd = true;
firstRow = true;
int imagewidth = 0;
//actual merging of images
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
if (odd)
{
if (firstRow)
{
g.DrawImage(img, 25, 25);
firstRow = false;
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
odd = false;
}
else
{
maxHeight = imageHeights.Max();
g.DrawImage(img, 25, maxHeight+50);
imagewidths.Add(width);
width = 0;
totalHeight = totalHeight + maxHeight + img.Height;
imageHeights.Clear();
imageHeights.Add(img.Height);
width += img.Width;
imagewidth = img.Width;
img.Dispose();
odd = false;
}
}
else
{
imageHeights.Add(img.Height);
g.DrawImage(img, width+50, maxHeight+50);
img.Dispose();
odd = true;
}
img.Dispose();
}
g.Dispose();
System.Drawing.Imaging.Encoder myEncoder =
System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
myEncoderParameters.Param[0] = myEncoderParameter;
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
img3.Save(finalImage, jpgEncoder, myEncoderParameters);
img3.Dispose();
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}

Compress image from web url in asp.net using c#

I'm trying to minify image from url, my code is this
public static string GetBreaker(string fileName)
{
string cacheBreaker = null;
try
{
if (fileName.StartsWith("~"))
{
fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName.Remove(0));
}
cacheBreaker = File.GetLastWriteTime(fileName).ToFileTime().ToString();
}
catch { }
return string.IsNullOrEmpty(cacheBreaker) ? string.Empty : string.Format("?cachebreaker={0}", cacheBreaker);
}
public static void SaveJpeg(string path, System.Drawing.Image img, int quality)
{
if (quality < 0 || quality > 100)
throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");
EncoderParameter qualityParam =
new EncoderParameter(Encoder.Quality, quality);
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
img.Save(path, jpegCodec, encoderParams);
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
for (int i = 0; i < codecs.Length; i++)
if (codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
protected void Button1_Click(object sender, EventArgs e)
{
System.Drawing.Image myImage = System.Drawing.Image.FromFile(ImageUrltxt.Text.ToString());
SaveJpeg(#"~/mintemp/demo.jpg", myImage, 50);
}
I'm getting error like this:
URI formats are not supported.
in
System.Drawing.Image myImage = System.Drawing.Image.FromFile(ImageUrltxt.Text.ToString());
Can anyone help me to solve out this problem. I'm very new to programming. Thanks in advance, sorry for my bad English.
1. First you have to check out your uri path is correct or not eg:
string uriPath = "file:\\C:\\Users\\john\\documents\\visual studio 2010\\Projects\\proj";
or
string localPath = new Uri(uriPath).LocalPath;
2. You have to add the uri of the image as correct Please check your uri path of image is correct.
SaveJpeg(#"~/mintemp/demo.jpg", myImage, 50);
3. This is coded in c# (for reference) resizing and compressing of image in c#
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private Boolean CheckFileType(String fileName)
{
String ext = Path.GetExtension(fileName) ;
switch (ext.ToLower())
{
case ".gif":
return true;
case ".png":
return true;
case ".jpg":
return true;
case ".jpeg":
return true;
case ".bmp":
return true;
default:
return false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
const int bmpW = 300;// //New image target width
const int bmpH = 226;// //New Image target height
if (FileUpload1.HasFile)
{
//Clear the error label text
lblError.Text = "";
//Check to make sure the file to upload has a picture file format extention
//and set the target width and height
if (this.CheckFileType(FileUpload1.FileName))
{
Int32 newWidth = bmpW;
Int32 newHeight = bmpH;
//Use the uploaded filename for saving without the "." extension
String upName = FileUpload1.FileName.Substring(0, FileUpload1.FileName.IndexOf("."));
//Mid(FileUpload1.FileName, 1, (InStr(FileUpload1.FileName, ".") - 1)) ;
//Set the save path of the resized image, you will need this directory already created in your web site
String filePath = "~/Upload/" + upName + ".jpg";
//Create a new Bitmap using the uploaded picture as a Stream
//Set the new bitmap resolution to 72 pixels per inch
Bitmap upBmp = (Bitmap)Bitmap.FromStream(FileUpload1.PostedFile.InputStream);
Bitmap newBmp = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
newBmp.SetResolution(72, 72);
//Get the uploaded image width and height
Int32 upWidth = upBmp.Width;
Int32 upHeight = upBmp.Height;
Int32 newX = 0; //Set the new top left drawing position on the image canvas
Int32 newY = 0;
Decimal reDuce;
//Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions
//to ensure the image is always in the centre of the canvas vertically and horizontally
if (upWidth > upHeight)
{
//Landscape picture
reDuce = newWidth / upWidth;
//calculate the width percentage reduction as decimal
newHeight = ((Int32)(upHeight * reDuce));
//reduce the uploaded image height by the reduce amount
newY = ((Int32)((bmpH - newHeight) / 2));
//Position the image centrally down the canvas
newX = 0; //Picture will be full width
}
else
{
if (upWidth < upHeight)
{
//Portrait picture
reDuce = newHeight / upHeight;
//calculate the height percentage reduction as decimal
newWidth = ((Int32)(upWidth * reDuce));
//reduce the uploaded image height by the reduce amount
newX = ((Int32)((bmpW - newWidth) / 2));
//Position the image centrally across the canvas
newY = 0; //Picture will be full hieght
}
else
{
if (upWidth == upHeight)
{
//square picture
reDuce = newHeight / upHeight;
//calculate the height percentage reduction as decimal
newWidth = ((Int32)((upWidth * reDuce)));
//reduce the uploaded image height by the reduce amount
newX = ((Int32)(((bmpW - newWidth) / 2))); //Position the image centrally across the canvas
newY = ((Int32)(((bmpH - newHeight) / 2))); //Position the image centrally down the canvas
}
}
}
//Create a new image from the uploaded picture using the Graphics class
//Clear the graphic and set the background colour to white
//Use Antialias and High Quality Bicubic to maintain a good quality picture
//Save the new bitmap image using //Png// picture format and the calculated canvas positioning
Graphics newGraphic = Graphics.FromImage(newBmp);
try
{
newGraphic.Clear(Color.White);
newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newGraphic.DrawImage(upBmp, newX, newY, newWidth, newHeight);
newBmp.Save(MapPath(filePath), System.Drawing.Imaging.ImageFormat.Jpeg);
//Show the uploaded resized picture in the image control
Image1.ImageUrl = filePath;
Image1.Visible = true;
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
throw ex;
}
finally
{
upBmp.Dispose();
newBmp.Dispose();
newGraphic.Dispose();
}
}
else
{
lblError.Text = "Please select a picture with a file format extension of either Bmp, Jpg, Jpeg, Gif or Png.";
}
}
}
}

I want to reduce image size before saving in my web folder in mvc4

I want to reduce image size and save reduced image to my image folder. Following is what I have done to save image but problem is reduce image is not saved into my image folder.
HOW TO SAVE reduced IMAGE IN MY IMAGE FOLDER IN MVC4..?
Below is my code to save the image:
public ActionResult AddProduct(TblProduct ObjProducts)
{
HttpPostedFileBase File = Request.Files[0];
if (ModelState.IsValid) {
string filename = Path.GetFileName(File.FileName);
string targetPath = Server.MapPath("Images/" + filename);
///save file
string oldImage = File.FileName;
string NewFileName = ObjProducts.ManualP_Id + ".JPG";
string pic = System.IO.Path.GetFileName(NewFileName);
string path = System.IO.Path.Combine(Server.MapPath("~/Images/ProductImg"), NewFileName);
File.SaveAs(path);
ObjProducts.Image =NewFileName;
ObjProducts.IsActive = true;
ObjProducts.IsDelete = false;
ObjProducts.CreatedDate = DateTime.Now;
db.TblProducts.Add(ObjProducts);
db.SaveChanges();
return RedirectToAction("DisplayProduct", "PanelProduct");
}
return View();
}
try this
Image img = Image.FromStream(httpPostedFileBase.InputStream, true, true);
var bitmap = new Bitmap(newWidth,newHeight);
using (Graphics g = Graphics.FromImage(bitmap)) {
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(img,
new Rectangle(0,0,newWidth,newHeight),
clipRectangle, GraphicsUnit.Pixel);
}
bitmap.Save(path,ImageFormat.Jpeg);
you can use below function to scale and compress your image to the desired resolution:
int Height = 600;
int Width = 800;
private Image Scale(Image imgPhoto)
{
float sourceWidth = imgPhoto.Width;
float sourceHeight = imgPhoto.Height;
float destHeight = 0;
float destWidth = 0;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
// force resize, might distort image
if (Width != 0 && Height != 0)
{
destWidth = Width;
destHeight = Height;
}
// change size proportially depending on width or height
else if (Height != 0)
{
destWidth = (float)(Height * sourceWidth) / sourceHeight;
destHeight = Height;
}
else
{
destWidth = Width;
destHeight = (float)(sourceHeight * Width / sourceWidth);
}
Bitmap bmPhoto = new Bitmap((int)destWidth, (int)destHeight,PixelFormat.Format32bppPArgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,new Rectangle(destX, destY, (int)destWidth, (int)destHeight),
new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight),GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}

Resize byte[] of Image

After reading from file dialog I want to resize a picture. I have the done the following code. Now I want to resize the stream of picture. How do I do it?
Stream stream = (Stream)openFileDialog.File.OpenRead();
byte[] bytes = new byte[stream.Length];
There is no need to declare a byte[], to resize an image just use
Image image = Image.FromFile(fileName);
check this other answer to see how to scale the image aftewards
try this
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
Usage
Image img = Image.FromStream(stream);
Image thumb = ScaleImage(img);
stream.Close();
stream.Dispose();
stream = new MemoryStream();
thumb.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
I have an picturebox. I load an image, resizing and conveting to byte at last sending to sqllite. Maybe it can be hlepfıull to you Code is below.
private static byte[] byteResim = null;
private void btnResimEkle_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Resimdosyası seçiniz.";
openFileDialog1.Filter = "Resim files (*.jpg)|*.jpg|Tüm dosyalar(*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string resimYol = openFileDialog1.FileName; // File name of the image
picResim.Image = Image.FromFile(resimYol);// picResim is name of picturebox
picResim.Image = YenidenBoyutlandir(new Bitmap(picResim.Image)); //this method resizing the image
Image UyeResim = picResim.Image; // and this four block converting to image to byte
MemoryStream ms = new MemoryStream();
UyeResim.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byteResim = ms.ToArray(); // byteResim variable format Byte[]
}
}
Image YenidenBoyutlandir(Image resim)// resizing image method
{
Image yeniResim = new Bitmap(150, 156);
using (Graphics abc = Graphics.FromImage((Bitmap)yeniResim))
{
abc.DrawImage(resim, new System.Drawing.Rectangle(0, 0, 150, 156));
}
return yeniResim;
}

Image resize without saving on disk

in asp.net i want to resize the image and display on some control but without saving on disk.
is there any free utility just like for clasic asp.
http://www.aspjpeg.com/livedemo.html
This Thumbnail class will do the job.
public class Thumbnail
{
private string _filePath;
private int _maxWidth = 120;
private int _maxHeight = 120;
public string MimeType;
public System.Drawing.Imaging.ImageFormat ImageFormat;
public byte[] ImageBytes;
public Thumbnail(string filePath, int maxWidth, int maxHeight)
{
_filePath = filePath;
_maxWidth = maxWidth;
_maxHeight = maxHeight;
MakeThumbnail();
}
private void MakeThumbnail()
{
using (Image img = new Bitmap(_filePath))
{
Size newSize = GenerateImageDimensions(img.Width, img.Height, _maxWidth, _maxHeight);
int imgWidth = newSize.Width;
int imgHeight = newSize.Height;
// create the thumbnail image
using (Image img2 =
img.GetThumbnailImage(imgWidth, imgHeight,
new Image.GetThumbnailImageAbort(Abort),
IntPtr.Zero))
{
using (Graphics g = Graphics.FromImage(img2)) // Create Graphics object from original Image
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
//BMP 0, JPEG 1 , GIF 2 , TIFF 3, PNG 4
System.Drawing.Imaging.ImageCodecInfo codec;
switch (Path.GetExtension(_filePath))
{
case ".gif":
codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[2];
ImageFormat = System.Drawing.Imaging.ImageFormat.Gif;
MimeType = "image/gif";
break;
case ".png":
codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[4];
ImageFormat = System.Drawing.Imaging.ImageFormat.Png;
MimeType = "image/png";
break;
default: //jpg
codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
MimeType = "image/jpg";
break;
}
//Set the parameters for defining the quality of the thumbnail... here it is set to 100%
System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
//Now draw the image on the instance of thumbnail Bitmap object
g.DrawImage(img, new Rectangle(0, 0, img2.Width, img2.Height));
MemoryStream ms = new MemoryStream();
img2.Save(ms, codec, eParams);
ImageBytes = new byte[ms.Length];
ImageBytes = ms.ToArray();
ms.Close();
ms.Dispose();
}
}
}
}
public static Size GenerateImageDimensions(int currW, int currH, int destW, int destH)
{
int imgWidth = currW;
int imgHeight = currH;
if (imgWidth > destW)
{
double rate = (double)imgWidth / (double)destW;
imgWidth = destW;
imgHeight = (int)(imgHeight / rate);
}
if (imgHeight > destH)
{
double rate = (double)imgHeight / (double)destH;
imgHeight = destH;
imgWidth = (int)(imgWidth / rate);
}
return new Size(imgWidth, imgHeight);
}
private bool Abort()
{
return false;
}
}
Using is simple, just put this on your page codebehind. Browser output will be resized image.
Thumbnail thm = new Thumbnail("c:\some_image.jpg", 300, 300);
Response.ContentType = thm.MimeType;
Response.BinaryWrite(thm.ImageBytes);
This is probably what you need:
http://imageresizing.net/

Categories