Monday, June 22, 2009

How to: Convert DIB to Bitmap

During the weekend a friend asked for some help on code to convert a DIB to a Bitmap in .NET, he had found some code in internet and it almost did everything he needed but the image was getting cut off along the sides, we figured the issue had something to do with getting the pointer to the bitmap, so we digged more and found some more code that then we had to make a couple fixes and changes to get it working. Since I was not able to find a full working solution to the problem I decided to write this post, I saw many people asking the same question in multiple forums so hopefully this will help

First, you’ll need to add System.Drawing.dll to the references of your project, then you’ll need to add the following uses clauses

//Name spaces needed
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;

the next step is to declare the BITMAPINFOHEADER structure, this can be declared outside your class:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BITMAPINFOHEADER
{
public uint biSize;
public int biWidth;
public int biHeight;
public ushort biPlanes;
public ushort biBitCount;
public uint biCompression;
public uint biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public uint biClrUsed;
public uint biClrImportant;

public void Init()
{
biSize = (uint)Marshal.SizeOf(this);
}
}

Then you need to import a function from GdiPlus.dll
//GDI External method needed Place it within your class
[DllImport("GdiPlus.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int GdipCreateBitmapFromGdiDib(IntPtr pBIH,
IntPtr pPix, out IntPtr pBitmap);

Now we can get to the actual code to conver the DIB to Bitmap, note the use of a helper function GetPixelInfo, this was the culprit of our issues, and the one we had a hard time finding then getting to work, the function BitmapFromDIB that you’ll find all over the web doesn’t have this code and so it doesn’t work in many cases, in fact the function that you'll find all over the place has a parameter pPix but it doesn't specify how to get this value. This code needs to be declared inside your class

//THIS METHOD SAVES THE CONTENTS OF THE DIB POINTER INTO A BITMAP OBJECT
private static Bitmap BitmapFromDIB(IntPtr pDIB)
{
//get pointer to bitmap header info
IntPtr pPix = GetPixelInfo(pDIB);

//Call external GDI method
MethodInfo mi = typeof(Bitmap).GetMethod("FromGDIplus", BindingFlags.Static | BindingFlags.NonPublic);
if (mi == null)
return null;

// Initialize memory pointer where Bitmap will be saved
IntPtr pBmp = IntPtr.Zero;

//Call external methosd that saves bitmap into pointer
int status = GdipCreateBitmapFromGdiDib(pDIB, pPix, out pBmp);

//If success return bitmap, if failed return null
if ((status == 0) && (pBmp != IntPtr.Zero))
return (Bitmap)mi.Invoke(null, new object[] { pBmp });
else
return null
;
}

//THIS METHOD GETS THE POINTER TO THE BITMAP HEADER INFO
private static IntPtr GetPixelInfo(IntPtr bmpPtr)
{
BITMAPINFOHEADER bmi = (BITMAPINFOHEADER)Marshal.PtrToStructure(bmpPtr, typeof(BITMAPINFOHEADER));

if (bmi.biSizeImage == 0)
bmi.biSizeImage = (uint)(((((bmi.biWidth * bmi.biBitCount) + 31) & ~31) >> 3) * bmi.biHeight);

int p = (int)bmi.biClrUsed;
if ((p == 0) && (bmi.biBitCount <= 8))
p = 1 << bmi.biBitCount;
p = (p * 4) + (int)bmi.biSize + (int)bmpPtr;
return (IntPtr)p;
}

finally, as a plus, what my friend actually needed was to convert from DIB to TIFF, so he wrote a function to do that, this function reuses the BitmapFromDIB function and allows you to set the image resolution

private void SavehDibToTiff(int hDIB, string fileName, int xRes, int yRes)
{
//Identify the memory pointer to the DIB Handler (hDIB)
IntPtr dibPtr = new IntPtr(hDIB);

//Save the contents of DIB pointer into bitmap object
Bitmap myBitmap = BitmapFromDIB(dibPtr);

//Set resolution if needed
if (xRes >0 && yRes>0)
myBitmap.SetResolution(xRes, yRes);

//Create an instance of the windows TIFF encoder
ImageCodecInfo ici = GetEncoderInfo("image/tiff");

//Define encoder parameters
EncoderParameters eps = new EncoderParameters(1); // only one parameter in this case (compression)

//Create an Encoder Value for TIFF compression Group 4
long ev = (long)EncoderValue.CompressionCCITT4;
eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, ev);

//Save file
myBitmap.Save(fileName, ici, eps);
}
//Helper to get Encoder from Windows for file type.
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}

and that is it, hoping this will help someone out there

Saturday, June 13, 2009

What are those colors on IE tabs?

colored tabs

I thought this was one of the best features in Internet Explorer 8, but not everyone gets the meaning of the colors on the tabs. The colors represent that the tabs are related, meaning that you followed a link from one page, IE opened another tab and assigned the same color as the previous tab, so that way the tabs that are derived from other tabs are now all grouped and it’s very easy to see this, very useful when you have multiple tabs open for different purposes. I just had to blog this because someone actually asked me what those colors were for, so I figured there’s more people who may have the same question.

Sunday, May 31, 2009

Silverlight how to: Add a user control to another user control

I'm starting to experiment with SilverLight and there's plenty of material out there, but some of the small details are really hard to find. The first application I'm working on requires a couple user controls, one embedded in the other and I spent a couple hours finding how to insert the user control into another control, then to the page, I thought it would be as easy as drag and drop but that didn't work, tried a few other things with no luck, turns out you have to add the namespace to the xaml, similar to the way you declare your controls in ASP.NET
The top xml of a user control (or the Page.xaml which is really just a user control) looks like this:

<UserControl x:Class="MyNameSpace.SomeUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="200" Height="300">

right after the last line with xmlns, you can type "xmlns:[prefix]=" (where [prefix] is the prefix you want to use in the xml to add your control, and make sure to add the = at the end); intellisense will do the rest, the first line of the drop down will contain the default namespace of your assembly, select that and you're good to go, it will look something like this:

<UserControl x:Class="MyNameSpace.SomeUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:prefix="clr-namespace:MyUserControl"
    Width="200" Height="300">

You can now start adding your control by typing <prefix: wherever you want to add your control and again intellisense will do the rest for you, you will be able to select any of the user controls that you have created previously under that namespace.
One last thing, if you will be referencing that user control from the code behind, you will need to name your control:

<prefix:MyUserControl Name="myControl" ></prefix:MyUserControl>

Doing so will give you strongly typed access to the instance of the control in your code behind, public members included

myControl.SomePublicMethod(someParameters);

Thursday, April 16, 2009

my solution to Eric Lippert's quiz

Eric posted a quiz a few days ago, it generated quite a number of responses, so I thought I would answer with the shortest possible C# answer (with my previous team we used to kinda compete on refactoring), so here it is (Justin and Paul, bring it on!):
The problem:
Write me a function that takes a non-null IEnumerable and returns a string with the following characteristics:

(1) If the sequence is empty then the resulting string is "{}".
(2) If the sequence is a single item "ABC" then the resulting string is "{ABC}".
(3) If the sequence is the two item sequence "ABC", "DEF" then the resulting string is "{ABC and DEF}".
(4) If the sequence has more than two items, say, "ABC", "DEF", "G", "H" then the resulting string is "{ABC, DEF, G and H}". (Note: no Oxford comma!)


My solution:

static string JoinStrings(IEnumerable<string> strings) {

int len = strings.Count();

return "{"+(

(len > 1) ?

strings.Take(len - 1)

.Aggregate((string head, string tail) => head+", "+tail)+

" and " +strings.Last()

: (len == 1) ?

strings.First()

: "")+

"}";

}

Thursday, April 02, 2009

public ASP.NET MVC { get; private set; }

For the 2 people who don't read many blogs (or twitter), but do read this one, yesterday it was announced that ASP.NET MVC 1.0 is open source baby! "Free like Speech." and there are no restrictions to the platform either, the license is MS-PL which provides broad rights to modify and redistribute the source code.

The first question that was raised was "can I submit patches?" and the answer is no, however nothing stops you from going and creating your own copy (forking) and start modifying it and redistributing it like this guy has already done.

You can get the source code here.

Did you know? Interface members are allowed to be private

This one comes as a surprise to most people, but it is possible to have a private implementation for an interface member, let's look at a very simple example, just for purposes of the ilustration.

public interface ITest {

void Test();

}

public class Test : ITest {

void ITest.Test() {

Console.WriteLine("test");

}

public void Test2() {

Console.WriteLine("test2");

}

}

class Program {

static void Main(string[] args) {

ITest t = new Test();

t.Test();

Test t2 = new Test();

//t2.Test(); //<<=== doesn't compile


If you don't believe it you can try it of course.

But why is this useful or how do you use this?

The technique allows you to ensure that the method is only visible to those who are using a variable of the interface type. All this does is to force the use of the member through an instance of the interface, meaning, for this example, if you want to get access to the .Test method, you can only do so through a variable of type ITest.

The only trick to make this work is to precede the member declaration with the Interface type as in:

void ITest.Test();

Not the most useful of tricks, but something to have on the bag of tricks, or maybe something to make you win a bet ;)

Friday, March 27, 2009

Do you want to view only the webpage content that was delivered securely? The simple guide

The post about the new dialog for secure/unsecure items in IE8 has had quite a few visits, so I thought I would make it much easier on the visitors to get to what they specifically need, I am guessing they are arriving here mainly to find out:
1 - What the heck does it mean.
2 - What they should do to see the full page.
3 - How can they get rid of the stupid message.
1 - What the heck does it mean?
They inverted the question from the previous dialog:
"This page contains both secure and nonsecure items.
Do you want to display the nonsecure items?"
So that more people will just click the default, and by doing so IE will not display the unsecure items on the page.

2 - I just want to see the entire page, what should I do?
Click NO

3 - How can I get rid of the stupid dialog once and for all?.
The short answer would be: Tools>internet options>security>custom level>display mixed content: Enable.
The long answer is on this other post: How to: Prevent the security dialog about unsecure items in IE

hope this helps! If I didn't answer what you were looking for, please let me know in the comments.

Friday, March 20, 2009

How to: Prevent the security dialog about unsecure items in IE

keywords: IE8, mixed, content, dialog, warning.

In my previous post about the new dialog in IE8 about mixed content, someone asked "How can I prevent this message from reappearing?", I thought it would be a good-to-have post and started writing this, but someone else already answered it (thanks Anonymous), in any case, here's what you need to do if you don't want to see that dialog:
tools>internet options>security>custom level>display mixed content: enable


Note that if the site you are visiting is NOT on the internet zone, you would have to make the changes to the appropiate zone:

here's how you tell which "zone" you are on, on the bottom right hand corner of the browser you should see something like this:


If you double click that, you can make changes to the other zones (Local Intranet, Trusted sites, restricted sites)



Just click the zone you want, and it will bring up the first dialog (from this post) where you can make the change.

This applies to IE8, IE7, IE6 (I don't know about older versions)

Do you want to view only the webpage content that was delivered securely?

keywords: IE8, usability, warning, error, dialog

Update: If you just care about making the dialog disappear go straight to comments or this post for more details, if you want the simple answers check the "simple guide". This post was originally intended for developers but it seems a lot of people are looking for an answer to this puzzle.

IE8 has been released and it's got a few really cool features as well as some really good protection mechanisms, all in all, a fairly good release.

But then I found this while navigating a secure page (Gmail)


Say what???

In what felt like I passed out I had to re-read the full dialog, then took me about 5 seconds to get what the dialog was telling me and about 10 to understand what would happen if I clicked NO.

I'm copying the contents of dialog text here just for SEO

This webpage contains content that will not be delivered using a secure HTTPS connection, which could compromise the security of the entire webpage.

Why did they change the previous dialog?:

This page contains both secure and nonsecure items.
Do you want to display the nonsecure items?



The new dialog seems very confusing to me, the extra text after the question just makes it even more confusing and for as long as I can remember we've had the same old dialog, which seemed fine.

Notice that even the answer is the opposite for the new dialog, maybe this is the reason it feels like asking a negative question.

I think the intent is for users to click the default yes, since 99.99% users don't really read any dialogs, and that will cause IE to not display the unsecure items on the page.

Wednesday, March 11, 2009

Pure Apple intuitiveness: The new iPod shuffle morse code control

I don't even have to try for this one, these are the instructions to operate the new iPod shuffle that has no controls on it, but defers that to the earphones, which is another WTF all on it's own


This are the buttons you get



You see, having a single button that performs so many different commands kinda defeats the purpose, imagine having an application with a single button to perform all the activities

update: Gizmodo calls it Morse code, I like it

Wednesday, March 04, 2009

Pure Mac intuitiveness: The keyboard

The newer Mac keyboards have 2 delete keys, but that's not the WTF (or maybe it is, but whatever).
I have some files on my desktop (is that what is called in Macland?) that I want to delete, so I select the files and hit the first delete key... nothing, the second delete key, nothing... WTF!!

After trying Ctrl, Option, Command, Shift and their combinations with the delete keys, finally found one that worked, I already forgot which one though.

How is that intuitive?

Monday, March 02, 2009

Pure Mac intuitiveness


I think I've had the worst luck with Macs in general; what you see here is a picture of Firefox on my iMac. Every single time I open Firefox, that's what I get and I have to grab that little window somewhere between the red and green little icons, drag it over to the left of my monitor, then make the window bigger. I think this started happening after I removed a monitor from the iMac.

Maybe it's just me, but I just don't see how that's intuitive.

By the way, I wanted to edit the image to add some more context but I didn't find an obvious way to edit the picture, neither from the context menu, or once on the preview, there's gotta be a way (you know, like in Windows, just right click, edit), is just doesn't seem to be all that intuitive.

Friday, February 20, 2009

Windows 7 installation: The product key does not match current Windows SKU

I just finished installing Windows 7 on my iMac, I had no problems during the installation until I got to the product key part, I grabbed a new key from the MS site, only to find out it didn't work, then I tried with another key, no luck, long story short, I tried at least 5 keys, including one I had already used to install it on my laptop, none of them worked.

Google has very few links to people who have had the problem, and the only answer seems to be that you may have downloaded the checked build, and you need to chose the Ultimate version; I had chosen Business edition.
Chris responds: You are probably installing from the "checked" ISO image. Please choose "Ultimate" and your key should work.
However, when you are on that screen there is no way to go back, do I don't know how you would select Ultimate.

Anyway, the solution that worked for me was to simply leave the field empty, yup, that simple.

So, if you downloaded the checked build, chose the Ultimate version; if you're stuck in that page, I hope this helps you

Friday, January 23, 2009

Windows 7 beta availability extended until Feb 10th

Due to the high interest in Windows 7, Microsoft has once more extended the download deadline

Because enthusiasm continues to be so high for the Windows 7 Beta and we don’t want anyone to miss out we will keep the Beta downloads open through February 10th. Customers who have started but not completed the download process will be able to do so through February 12th.

This will give you more than enough time if you want to try the beta. There are good reviews everywhere you look, so if you haven't decided, you are missing out a lot, especially if you are using Windows Vista. It is important to note that product keys will be available even after that

Product keys for the Windows 7 Beta will continue to be available. So if you have the Windows 7 Beta but didn’t get a product key you will be able to do so even after February 12th.

MSDN and Technet subscribers need not to worry about any dates as they will have access throughout the entire Windows 7 Beta phase

download link

Monday, January 19, 2009

Multiple profiles per user in twitter

Don't get too excited, that's just my proposal for twitter;

I would like to see something like

http://twitter.com/BlackTigerX/technical
http://twitter.com/BlackTigerX/personal
http://twitter.com/BlackTigerX/family

I think there are many benefits to this

  1. There are some of us using multiple accounts, one for each language.
  2. Some people even use different social networks similar to twitter, one for each aspect.
  3. When I subscribe to someone I only care about X (technical, personal), not Y.
  4. Noise reduction, big one.
  5. Would enable twitter searches on specific "tags" to find more relevant content.
Each profile could be protected to only allow the people you want, they could even be invisible so only the people you want even know about it.

People could subscribe to all public profiles if they wanted to.

The twittering tools would have to change a bit, just to specify which "tag" or specific profiles to tweet to.

I think it would reduce the noise considerably since the same account now allows you to deliver content in different branches.

I'm getting more and more ideas, the more I think about it, the more I like it.

oh, and yes, that's my twitter profile...(sigh, in English for technical content)

Sunday, January 11, 2009

Windows 7 beta availability extended until Jan 24th

If you haven't been able to download Windows 7 beta you can still get it; due to the high demand MS has extended the availability to 2 more weeks and they won't limit it to a fixed number of downloads.

Due to an enormous surge in demand, the download experience was not ideal so we listened and took the necessary steps to ensure a good experience. We have clearly heard that many of you want to check out the Windows 7 Beta and, as a result, we have decided remove the initial 2.5 million limit on the public beta for the next two weeks (thru January 24th). During that time you will have access to the beta even if the download number exceeds the 2.5 million unit limit.


you can download it here
source: Windows Team Blog

Saturday, January 10, 2009

About the new Google favicon

Google just rolled out a new favicon, in this picture we can see all 3 favicons they've had

The icon that was originally submitted was this:
André Resende, a computer science undergraduate student at the University of Campinas in Brazil, submitted the design that inspired our new favicon
It seems to me the original favicon was much better than the one they came up

The one they chose feels too noisy, what do you think?

source

Friday, January 09, 2009

Windows 7 beta now avaiable to the public (first 2.5 million downloaders)

They are going to go fast, so if you want to try it, go get it now

Thursday, January 08, 2009

First post from Windows 7 beta



I'm running Windows 7 beta 64bit on my Mac using VMWare Fusion, even in this configuration things are looking pretty good, definitely a good improvement over Vista, they got rid of a lot of the UAC popups in areas where it just makes sense that way. The new task bar seems pretty good, it will take me a little bit getting used to, but mostly because I use it different than most users. My quick launch is gone!! I'm definitely going to need my quick launch back (I think).

I love the snipping tool, similar to the one found in Mac, users who have always used Windows will find it really nice, is like a print screen on steroids, you can capture free form, rectangular area, window, and full screen; very intuitive and very fast, pretty much instant

Perhaps this is what Vista should've been, so far all the reviews I have seen have been very positive in all areas, this post is just another "me too!"

Windows 7 beta available for MSDN and Technet subscribers

all the reviews say it is really good, what are you waiting for

oh that's right, no MSDN subscription, don't worry, it will be available to the public on friday

of course you could also find it on Bittorrent (just be careful)