how get width and height of Image control - asp.net

I want to change the size of my image in asp.net proportionally, the problem is that I can't get the actual size of the image which is loaded from database. here is the code:
imgAvatar.ImageUrl = "~/Modules/FileViewer.ashx?id=" + o.EventID;
double r = imgAvatar.Width.Value / 300.00;
imgAvatar.Width = new Unit(300, UnitType.Pixel);
imgAvatar.Height = new Unit(imgAvatar.Height.Value / r, UnitType.Pixel);
but the imgAvatar.Width.Value is always 0.0.
what would you suggest to me?

Do not set width and height. The rendered IMG tag will be sized to the size of downloaded image.
However, if the image is too large you might have a problem. In that case, use CSS to set max:
max-width: 300px;
max-height: 300px;
I might have misunderstand the question, considering my answer above. Anyways, the way I see that done would be similar to this:
System.Drawing.Image image = System.Drawing.Image.FromFile(this.Server.MapUrl("~/image path here"));
// sorry if the above line doesn't compile; writing from memory, use intellisense to find these classes/methods
// image.Width and image.Height will work here

Takes the size of the image with Bitmap and calls the below function to resize
Bitmap myBitmap;
string fileName = "foreverAlone.jpg";
myBitmap = new Bitmap(fileName);
Size newSize = NewImageSize(myBitmap.Height, myBitmap.Width, 100);//myBitMap.Height and myBitMap.Width is how you take the original size
Check BitMap class here Bitmap Class - MSDN Article
This code returns new size of the image, and image quality remains the same -no reduce-, FormatSize parameter decides the new size.
public Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)
{
Size NewSize;
double tempval;
if (OriginalHeight > FormatSize && OriginalWidth > FormatSize)
{
if (OriginalHeight > OriginalWidth)
tempval = FormatSize / Convert.ToDouble(OriginalHeight);
else
tempval = FormatSize / Convert.ToDouble(OriginalWidth);
NewSize = new Size(Convert.ToInt32(tempval * OriginalWidth), Convert.ToInt32(tempval * OriginalHeight));
}
else
NewSize = new Size(OriginalWidth, OriginalHeight);
return NewSize;
}

Related

Why does Image.GetThumbnailImage work differently on IIS6 and IIS7.5?

Bit of a strange question and I don't know whether anyone will have come across this one before.
We have a ASP.net page generating physical thumbnail jpeg files on a filesystem and copying fullsize images to a different location. So we input one image and we get a complete copy in one location and a small image 102*68 in a different location.
We're currently looking to finally move away from IIS6 on Server 2003 to IIS7.5 on Server 2008R2, except there's on problem.
On the old system (so IIS6/Server 2003) the black borders are removed and the image stays at the correct ration. On the new system (IIS7.5/Server 2008) the thumbnails are rendered exactly as they exist in the JPEG, with black borders, but this makes the thumbnail slightly squashed and obviously includes ugly black borders.
Anyone know why this might be happening? I've done a google and can't seem to find out which behaviour is "correct". My gut tells me that the new system is correctly rendering the thumbnail as it exists, but I don't know.
Anyone have any suggestions how to solve the problem?
I think as suggested it is the .net differences. not IIS.
Just re write your code, your save a lot of time, very simple thing to do.
Here is a image handler i wrote a while ago that re draws any image to your settings.
public class image_handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// set file
string ImageToDraw = context.Request.QueryString["FilePath"];
ImageToDraw = context.Server.MapPath(ImageToDraw);
// Grab images to work on's true width and height
Image ImageFromFile = Image.FromFile(ImageToDraw);
double ImageFromFileWidth = ImageFromFile.Width;
double ImageFromFileHeight = ImageFromFile.Height;
ImageFromFile.Dispose();
// Get required width and work out new dimensions
double NewHeightRequired = 230;
if (context.Request.QueryString["imageHeight"] != null)
NewHeightRequired = Convert.ToDouble(context.Request.QueryString["imageHeight"]);
double DivTotal = (ImageFromFileHeight / NewHeightRequired);
double NewWidthValue = (ImageFromFileWidth / DivTotal);
double NewHeightVale = (ImageFromFileHeight / DivTotal);
NewWidthValue = ImageFromFileWidth / (ImageFromFileWidth / NewWidthValue);
NewHeightVale = ImageFromFileHeight / (ImageFromFileHeight / NewHeightVale);
// Set new width, height
int x = Convert.ToInt16(NewWidthValue);
int y = Convert.ToInt16(NewHeightVale);
Bitmap image = new Bitmap(x, y);
Graphics g = Graphics.FromImage(image);
Image thumbnail = Image.FromFile(ImageToDraw);
// Quality Control
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.DrawImage(thumbnail, 0, 0, x, y);
g.Dispose();
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
image.Dispose();
}
public bool IsReusable
{
get
{
return true;
}
}

How do you get the line height of the text in a Spark Label?

How do you determine the line height (in pixels) of the text in a Spark Label?
keyle's answer will only give you the height of the text, not the actual 'lineHeight' style. You can easily get that style like this:
myLabel.getStyle("lineHeight");
The problem is that this can return a relative value (a percentage) or an absolute value (in pixels). The default - if no lineHeight was explicitely set - is "120%".
So here's how we can get the value in pixels in both cases:
var lineHeightStyle:* = myLabel.getStyle("lineHeight");
//its already a value in pixels
if (lineHeightStyle is Number) var lineHeight:Number = lineHeightStyle;
//it's a relative value: let's calculate
else {
var lineMetrics:TextLineMetrics = myLabel.measureText(myLabel.text);
//get the numeric value from the string and divide it by 100
var ratio:Number = int(lineHeightStyle.match(/\d+/)[0]) / 100;
lineHeight = lineMetrics.height * ratio;
}
Have you tried the following?
var lineMetrics:TextLineMetrics = label.measureText(label.text);
var result:Number = lineMetrics.height;

Set image size in powerpoint using open xml

Im am generating a ppt-file using this tutorial here
Step 4 describes how to swap out the image placeholder.
My images has different dimensions, which makes some images look a little bit too funny.
Is there any way to resize the placeholder so it can keep the dimensions?
Edit: Ok, a better explanation: users can upload images of them selves. The images are stored on the server. I am generating a ppt-file with one user per slide. And for every slide there will be an image, if any. I can of course get the dimensions of every image, but how do I replace the placeholder with an image of another dimension than the placeholder?
Well, I can't tell you based on that tutorial, but I can tell you where it is done in Open XML (i.e. not the SDK).
Your picture will have an xfrm element with a set of values, like this:
<p:spPr>
<a:xfrm>
<a:off x="7048050" y="6248401"/>
<a:ext cx="972000" cy="288000"/>
</a:xfrm>
</p:spPr>
The values you want to change are the cx and cy of a:ext. Take your new picture's dimensions (h and w) from like a System.Drawing.Image object and take each of the values and multiply by 12700. So if the width of the picture is 400 pixels, the cx value of a:ext will be (400 x 12700 = 5080000).
This is how I did it:
using DocumentFormat.OpenXml.Packaging;
lets assume you have your SlidePart
In my case I wanted to check for the alt title of the pictures and replace them if it matches to my key.
//find all image alt title (description) in the slide
List<DocumentFormat.OpenXml.Presentation.Picture> slidePictures = slidePart.Slide.Descendants<DocumentFormat.OpenXml.Presentation.Picture>()
.Where(a => a.NonVisualPictureProperties.NonVisualDrawingProperties.Description.HasValue).Distinct().ToList();
now we check all the images:
//check all images in the slide and replace them if it matches our parameter
foreach (DocumentFormat.OpenXml.Presentation.Picture imagePlaceHolder in slidePictures)
now in the loop we look for Transform2D and modify it with our value:
Transform2D transform = imagePlaceHolder.Descendants<Transform2D>().First();
Tuple<Int64Value, Int64Value> aspectRatio = CorrectAspectRatio(param.Image.FullName, transform.Extents.Cx, transform.Extents.Cy);
transform.Extents.Cx = aspectRatio.Item1;
transform.Extents.Cy = aspectRatio.Item2;
And this function looks like this:
public static Tuple<Int64Value, Int64Value> CorrectAspectRatio(string fileName, Int64Value cx, Int64Value cy)
{
BitmapImage img = new();
using (FileStream fs = new(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
img.BeginInit();
img.StreamSource = fs;
img.EndInit();
}
int widthPx = img.PixelWidth;
int heightPx = img.PixelHeight;
const int EMUsPerInch = 914400;
Int64Value x = (Int64Value)(widthPx * EMUsPerInch / img.DpiX);
Int64Value y = (Int64Value)(heightPx * EMUsPerInch / img.DpiY);
if (x > cx)
{
decimal ratio = cx * 1.0m / x;
x = cx;
y = (Int64Value)(cy * ratio);
}
if (y > cy)
{
decimal ratio = cy * 1.0m / y;
y = cy;
x = (Int64Value)(cx * ratio);
}
return new Tuple<Int64Value, Int64Value>(x, y);
}
Important thing to note is that EMU per inch is 914400. In most cases you just need to divide it by 96, but for some monitors it is different. Therefore it is best to divide it the DPI for x and y.

image management in asp.net?

in my application i am uploading the image into database. before it is store in the database, i want to do image management like decreasing size and decreasing height and width of the image. can u help me. is there any source code or any reference please.
What codebehind language are you using?
I find 4guysfromrolla to be a good ASP.NET reference, try this article for starters:
https://web.archive.org/web/20211020111640/https://www.4guysfromrolla.com/articles/012203-1.aspx
If you're talking about something like creating a thumbnail image. the Image() class will let you scale an existing image up or down. YMMV.
You want to be looking at the System.Drawing name space for manipulating images with ASP.NET. You can load any supported image file type (i.e. jpg, gif, png, etc) using Image.FromFile(), Image.FromStream(), etc. From there you use the Drawing Graphics context to manipulate the image. To give you a flavour here is my resize image function:
// Creates a re-sized image from the SourceFile provided that retails the same aspect ratio of the SourceImage.
// - If either the width or height dimensions is not provided then the resized image will use the
// proportion of the provided dimension to calculate the missing one.
// - If both the width and height are provided then the resized image will have the dimensions provided
// with the sides of the excess portions clipped from the center of the image.
public static Image ResizeImage(Image sourceImage, int? newWidth, int? newHeight)
{
bool doNotScale = newWidth == null || newHeight == null; ;
if (newWidth == null)
{
newWidth = (int)(sourceImage.Width * ((float)newHeight / sourceImage.Height));
}
else if (newHeight == null)
{
newHeight = (int)(sourceImage.Height * ((float)newWidth) / sourceImage.Width);
}
var targetImage = new Bitmap(newWidth.Value, newHeight.Value);
Rectangle srcRect;
var desRect = new Rectangle(0, 0, newWidth.Value, newHeight.Value);
if (doNotScale)
{
srcRect = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
}
else
{
if (sourceImage.Height > sourceImage.Width)
{
// clip the height
int delta = sourceImage.Height - sourceImage.Width;
srcRect = new Rectangle(0, delta / 2, sourceImage.Width, sourceImage.Width);
}
else
{
// clip the width
int delta = sourceImage.Width - sourceImage.Height;
srcRect = new Rectangle(delta / 2, 0, sourceImage.Height, sourceImage.Height);
}
}
using (var g = Graphics.FromImage(targetImage))
{
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(sourceImage, desRect, srcRect, GraphicsUnit.Pixel);
}
return targetImage;
}
You can either use the image class or a 3rd party DLL such as ASPJPEG. A few ASPJPEG samples can be found here. I do a lot of image processing and my host reliablesite supports this dll on their servers.

How to automatically set TextField()'s width

I'm trying to set the width of a Textfield() object based on it's string content that I have set-
Is there a way to dynamically set this once the string has been sent to the object?
I have:
var t1:TextField = new TextField()
t1.x = stage.stageWidth / 2;
t1.y = stage.stageHeight / 2;
t1.text = "some string that i would want to render";
t1.textColor = 0x000000;
t1.cacheAsBitmap = true;
addChild(t1);
Thanks for any suggestions...
jml
TextField.autoSize?
edit:
You should read the documentation correctly, it's a member variable that actually needs to be set. I'll give you a quick example on how this works:
var tf:TextField = new TextField();
tf.text = 'Some text.';
tf.autoSize = TextFieldAutoSize.LEFT;
tf.x = ( stage.stageWidth - tf.width ) / 2;
tf.y = ( stage.stageHeight - tf.height ) / 2;
Alternatively you can also align the text field first and use TextFieldAutoSize.CENTER to keep it aligned in the center.
t1.text = "Some text";
t1.width = t1.textWidth + 5;
t1.height = t1.textHeight + 5;
Why the + 5? Because Adobe sucks and adds an internal gutter around your stuff. Per the docs this is supposed to be 2px per side, but it's actually slightly more, so you add another +1 for good measure.
you could try using the getCharBoundaries() method (it returns a rectangle surrounding a character at a specified index). Use that to get the rectangle from the first and last chars and set the width to the difference of those rectangles.
Pretty convoluted, there's got to be a better way, but if not this should work.

Resources