Page 1 of 18 123411 ... LastLast
Results 1 to 40 of 710

Thread: [vb6]Alpha Image Control v2 - Final Update (15 Jan 2012)

Hybrid View

  1. #1

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    [vb6]Alpha Image Control v2 - Final Update (15 Jan 2012)

    NOTICE :: NOTICE :: NOTICE

    Version 2 of the control came to an end. No new enhancements will be added to version 2. Bug fixes may be applied as they are discovered. Support for version 2 will eventually cease.

    Version 3 of the control will replace version 2 and will be DPI-aware. This will result in how images are loaded and displayed on a PC based on DPI settings (XP and above). In the case of icons/cursors, it may also result in which sized icon is displayed, based on current DPI settings. Externally, how you use this control will not change very much. Internally, a logical coordinate space will be used for all measurements and storage of properties, unlike the physical coordinate space now used. Like VB, this control will use twips internally. Externally to control users, pixels will still be used. DPI awareness will also be a customizable property. To properly support DPI-awareness, binary compatibility will be broken; hence a new version.
    __________________________________________________________

    15 Jan 2012. Minor patch applied. See change history below
    ----------------------------------------------------------

    Purpose: A control that allows viewing & creating many image formats, particularly alpha-blended ones.
    This control is very similar in appearance and functionality to VB's Image Control. However, this control is super-sized. Requires GDI+ on the computer. Not a major issue nowadays. And GDI+ v1.0 can be redistributable if it doesn't exist. Advanced effects supported if system has GDI+ v1.1 installed (see posts #2 & 3 below).

    Image formats supported: PNG (animated PNG too), TIFF (multi-page ones too), Icons, Cursors, Animated Cursors, JPEG, TGA, GIF (all frames), Bitmap, WMF, EMF, PCX, PBM, PGM, PPM, PAM, AVI, and those same formats contained inside MP3/WMA files, if they can be parsed out.

    Image sources supported: Files (unicode supported), arrays, stdPicture object, Clipboard object, Screen object (snapshots), OLE Drag/Drop Data object, this control's .Picture property, VB's LoadResData/LoadResPicture functions, bitmap/icon handles and URLs to images (unicode & async requests supported). Also can extract images from binaries such as exe, dll and ocx files. Supports loading images from strings containing Base64 encoding. Control can now be data-bound to a database table/field.
    See LoadPictureGDIp.rtf & SavePictureGDIp.rtf files included in zip.

    For more advanced users: special Pre & Post painting events allow you to modify the control's content during its rendering process. This literally allows the control to act as a blank canvas. Don't respond to those events & image renders as usual. Respond and you can change the background before image is rendered & even prevent image from rendering; you can also modify the control after the image is rendered but before it is displayed. Two of the sample projects use those events to show how powerful they are.

    Unlike VB's image control, a few global methods are designed to allow you to draw directly to any DC you desire. TilePictureGDIplus will tile a source image and can fill a form very quickly. PaintPictureGDIplus will draw an image to any DC. The control, itself, has a method to draw itself to another DC also: PaintControlAsDrawnToHDC. Additionally, there are methods that can be used for non-drawing: the UnicodeFileDialog class can be used from your project; giving you a unicode-aware common dialog substitute. The global ConvertRGBtoARGB & ConvertARGBtoRGB methods are useful conversion utilities that also accept VB system colors (i.e., vbButtonFace). The global GetScaledContainerSize & GetScaledImageSize methods are useful for scaling a container to image or vice versa. As long as the global GDIplusTokenExists method returns true, you never have to create your own GDI+ startup/shutdown routines; the GDIplusTokenVersion method lets you know which version of GDI+ is running

    ** Control performance is degraded while uncompiled. When compiled, you will experience far better performance

    Recommend you open the AICGlobals class and read the detailed comments for usage of the main functions. You can get more information about the control's properties, methods and events by reading the code or using your Object Browser (F2).
    See next post for a summary of the properties, methods, and classes this control exposes.

    To add an image during design time, simply add a control to the form, right click on it, and select Properties.
    You can also double click on the "Custom" property sheet item.


    Look closely at the screenshot below.
    See toucan's shadow over the playing card? See the grid dots in the shadows?
    That's alpha-blending at work!!!

    Name:  screenshot.png
Views: 38067
Size:  225.4 KB

    Following is history of most recent changes. The control itself has complete change history included
    Any changes to the control may have spawned updates to 1 or more sample projects.
    Code:
    15 Jan 2012, version 2.1.32: Final update barring bugs
    - UnicodeBrowseFolders class can now be created/called from within your projects
    - Property page could return 32 & 48 sized associated icons in PNG format & shouldn't. Fixed
    8 Jan 2012, v2.1.31
    - property page for dragged/pasted files now coded to have them relate to associated icons, as appropriate
    7 Jan 2012, v2.1.30
    - can load icons associated with file system objects
    - modified property page for associated icon selection
    - added ASSOCIATEDICON structure, SHILIconSizeEnum & AssocIconTypeEnum enumerations
    - added UnicodeBrowseFolders global class
    - updated LoadPictureGdip & SavePictureGDIp RTF files
    - fixes a logic error where control may not resize while it is hidden
    - fixes issue where app may create metafile of text copied to clipboard & control loads that metafile instead of using the text to load an image
    26 Nov 2011, v2.1.29
    - Error converting black/white icons/cursors when loaded by handle. Fixed
    16 Nov v2.1.28
    - Allows saving unmodified AVI to other destinations (i.e., file, array, etc) 
    - Found & fixed several minor bugs
      -- cFunctionsICO.HICONtoArray custom header changes prevented loading icons by handle
      -- cFunctionsPNM.LoadPNMResource invalid flag setting could invert PBM formats
      -- cFunctionsPNM.pvBuildPNM saved invalid token when writing 32 bpp alpha PAM formats
      -- cFunctionsTGA.SaveAsTGA could save image upside down
      -- cFunctionsPCX.SaveAsPCX could save image upside down
    - Property page did not offer AVI as an image source
    7 Nov v2.1.27
    - test code from a few versions ago remained by mistake. Could crash project. Fixed
    6 Nov v2.1.26
    - error in MP3 tag parsing routine could occur with tags of less than 30 bytes. Fixed
    3 Nov v2.1.25
    - added WMA files as an image source
    - enabled control to be bound to a database table/field. See LoadPictureGDIp.RTF for more
    - added UpdateDataboundImage event to allow changing what will be saved before image written to database (databound control)
    - rewrote the MP3 parsing logic; more robust & should properly handle v2,3,4 ID3 tags + unsynchronized tags
    For the 8 sample projects provided...
    1) Open the uncompiled alpha image project first (contained in the AlphaImgControl.zip file)
    2) From the IDE menu: File | Add Project
    3) Navigate to & select a sample project
    4) Right click on it in the project explorer (treeview) & select: Set as Start Up
    Now run the sample project. When done playing, remove the sample project, navigate to one of the others & run it.
    Ensure you change the start-up project. You do not want the attached image control as the start-up project.

    You will really like the "custom buttons" project. Shows how flexible this control really is.
    Note: Sometimes I occasionally get an error when trying to load a sample project. This almost always happens after I've modified the uncompiled alpha image control. If that happens to you, simply close the sample project without saving changes, close the alpha image control project. Now try again.

    Tips
    1. Extract both zips, into same parent folder, using the "Use Folder Names" option
    2. When recompiling this control over an existing, compiled, version always opt for Binary Compatibility from the project properties window, on the Component tab. See this thread for a bit more information on binary compatibility. Binary compatibility if used allows already compiled/distributed apps using the control to continue using a newer version when it is distributed. I will make every effort in future revisions to maintain binary compatibility.
    Attached Files Attached Files
    Last edited by LaVolpe; Jan 15th, 2012 at 12:06 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  2. #2

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control

    Note that the control is basically a GUI wrapper of the GDIpImage class.

    The following is a summary of control properties/methods:
    :: listing replaced by the ControlProps.rtf file included with the project's zip file in post #1

    The following are custom events fired from the control:
    :: listing replaced by the ControlProps.rtf file included with the project's zip file in post #1

    The following are global functions that are not specific to any control:
    AsyncAbortDownloads: Aborts all active and/or queued async download requests
    AsyncDownloadsEnabled: Returns whether async downloads can be performed
    AsyncGetDownloadStates: Returns how many async requests are in progress, waiting on replies, and/or queued
    AVIEnabled: Property returns true if AVIs can be read (i.e., expected DLLs loaded)
    CF_AlphaImageCtl: Returns the custom clipboard format used by this control.
    ConvertBGRAtoRGB: Returns RGB format from GDI+ color format
    ConvertRGBtoBGRA: Returns color format used by most GDI+ functions
    GDIplusTokenExists: Returns whether GDI+ successfully loaded or not
    GDIplusTokenVersion: Returns the GDI+ version loaded. v1.1 enables advanced effects
    GetPixelGDIplus: Returns RGB color from a point within the image
    GetScaledContainerSize: Returns container size needed to display scaled image at any rotation
    GetScaledImageSize: Scales dimensions to another allowing consideration for rotation
    LoadPictureGDIplus: Loads most image formats into a GDIpImage class
    MergePictureGDIplus: Combines/overlays two or more images
    PaintPictureGDIplus: Renders an image to any DC using various rendering styles
    SavePictureGDIplus: Saves an image to a variety of destinations/formats using various rendering styles
    SetPixelGDIplus: Sets a point within the image to a user-defined color
    TilePictureGDIplus: Tiles an image to any DC or to a new GDIpImage class

    Objects you can create and use dynamically:

    UnicodeBrowseFolders Class: A unicode-aware "browse for folder" dialog class you can use from within your code.

    UnicodeFileDialog Class: A unicode-aware Open/Save dialog class you can use from within your code.

    GDIpEffects Class: A class used to create GDI+ image attributes and v1.1 effects
    --- Class has its own functions/properties to enable these attributes/effects
    :: Image Attributes created with: GrayScale, GlobalTransparencyPct, LightnessPct, BlendColor, BlendPct, TransparentColor & TransparentColorUsed properties
    :: Functions provided to create effects: Blur, HueSaturationLightness, Sharpen, BrightnessContrast, ColorBalance, ColorCurve, Tint, ToneLevel, & RedEyeCorrection properties (requires GDI+ v1.1)

    GDIpImage Class: A class assigned to a control. Can also be created and used dynamically, just like a VB stdPicture object
    --- Class has its own functions that allow some customizing...
    AlphaMask: Gets/Sets the alpha values of an image
    AnimationLoops: Returns number of loops from a loaded animated GIF/PNG resource, if provided by that resource
    AsyncDownloadDone: Event that occurs when async download successful or fails
    AsyncDownloadStatus: Property that returns whether download successful, failed, in progress
    AsyncDownloadURL: Property returns URL passed to async download request. URL available until the ASyncDownloadDone event exits.
    BitDepth: Returns the bit depth used by the image class. Optional Index parameter allows checking on other frames
    ExtractImageData: Extracts image data to a byte array
    FrameDuration: Returns the frame duration. Optional Index parameter allows checking on other frames.
    Handle. Returns the GDI+ handle created from the loaded image
    Height: Returns the image/segmented height in pixels. Optional Index parameter allows checking on other frames
    ImageCount: Returns the number of frames loaded for this image
    ImageFormat: Returns the image format (ImageFormatEnum value)
    ImageGroup: Returns/sets the current Image group (Win7+ animated cursors)
    ImageGroups: Returns the number of image groups for the loaded image
    ImageGroupFormat: Returns the format of an Image Group. Binaries can have 3 different groups each their own format (bmp, ico, cur)
    ImageIndex: Returns/sets the current image frame index
    KeepOriginalFormat: Returns if original source data cached with the image or releases that data
    Left: Returns the image's Left position. Useful for Segmented images, else will be zero
    RegionFromImage: Returns a region containing just opaque pixels of the current image
    Render: Draws the image to any hDC, using optional rendering styles and user-defined GDI+ objects
    RenderSkewed: Draws the image to any hDC, using optional rendering styles and user-defined GDI+ objects. Rendered image is a parallelogram similar to GDI's PlgBlt API
    SegmentImage: Removes/creates tiles within an image, offering more options than the AlphaImgCtl's related function
    Segmented: Returns whether the loaded image has been segmented or not
    Top: Returns the image's Top position. Useful for Segmented images, else will be zero
    UsesTransparency: Returns whether current image frame contains transparency or not
    Width: Returns the image/segmented width in pixels. Optional Index parameter allows checking on other frames

    Note that this class is the control's Picture property.
    You have access to its properties and methods by referencing it.
    Example: MsgBox "Uses the Alpha Channel?: " & AlphaImgCtl2.Picture.UsesTransparency
    Last edited by LaVolpe; Jan 7th, 2012 at 03:49 PM. Reason: updated descriptions
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  3. #3

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control

    Tips and comments regarding usage

    MEMORY LEAKS!!!
    When control is not compiled, you can experience memory leaks and even random GDI+ crashes.
    This can/will happen when you run your project, using the uncompiled control, and do not close your project normally. Whenever you hit END either as a result of a Debug message box option, clicking the blue square 'stop' toolbar button or actually executing an End statement in code, you are abnormally terminating your application. This results in the uncompiled control not having its class/usercontrol Terminate events triggered by VB. And guess where the clean up code is, it's in the Terminate events. This problem does not exist when the control is compiled.

    Scale Mode
    This control, like GDI and GDI+, requires dimensions and offsets in pixels not twips. Failiing to provide pixel sizes to the control can end up with unexpected results. For example, trying to call TilePictureGDIplus on a full-screen form and passing Me.ScaleWidth while form's scale mode is twips attempts to create a tiled image of ScreenSize*15 (1 twip ~ 15 pixels). This will most likely fail. Same issue if you are using the width/height of the AlphaImgCtrl. The dimensions of any control are in the scale mode of the control's container. Suggestion: Either ensure the control's container scale mode is pixels or use ScaleX,ScaleY to convert that scale mode to pixels.
    Tip: VB Frames do not have scalemode properties & the scalemode is always Twips. You will have to use ScaleX,ScaleY to convert a frame-contained control's dimensions to pixels.

    v1.1 of the GDI+ library
    Vista+ only. If you want to play with v1.1 of GDI+, this is how I managed it. This thread, reply #53, contains information on how to ensure v1.1 is used with your compiled application. The manifest can also be placed alongside your vb6.exe if named vb6.exe.manifest and v1.1 will be available during design time too. Note about the vb6.exe.manifest: if you have multi-boot system and XP & Vista installed VB6 to the same folder, that manifest will prevent VB from loading when you boot to XP. Simply rename the file

    During runtime you can query the version loaded with GDIplusTokenVersion. During design-time, bring up the property pages of any alpha image control and click on the 2nd property page. If the Create command button is enabled, v1.1 is loaded.

    Sharing Images
    During run-time, you may want 2 or more controls to display the same image. By sharing images, you reduce resources since only 1 copy of the image data and only 1 GDI+ image handle is created, no matter how many controls are sharing that image.
    To Share: Set AlphaImgCtl2.Picture = AlphaImgCtl1.Picture
    Applies to BkgImage property too: Set AlphaImgCtl2.BkgImage = AlphaImgCtl1.BkgImage

    During design-time, if 2 or more controls will display same image, set the image in just 1 control. During run-time share the image, during Form_Load, as just mentioned. Each image assigned at design-time will be stored by each control. Why store the same image multiple times?
    When sharing. Some things effect all controls that share the image and these are:
    -- Animating one, animates all controls sharing that image
    -- If image contains multiple images (icon, cursor, gif, tiff), changing index or group changes all controls
    -- If segmenting image, all controls show segmented image

    Animation
    Obviously animation means your image will change quite often, sometimes several times per second.
    There are some actions I would recommend against while animating.
    - Don't use FastRedraw. Each time image frame changes, image drawn to offscreen DC first, then to DC. Waste of resources/time IMO
    - Don't use HitTest type of lvicTrimmedImage. To determine trimming, image pixels must be pre-processed. Waste of time
    - Don't use HitTest type of lvicRunTimeRegion. Whatever region you supplied may not align with new frame's image
    - Avoid using AutoSize if not necessary. Each frame requires the control to be re-examined for possible resizing
    - Avoid overlapping any control with the animating control. See performance below.
    - If tracking MouseEnter/Exit, they can trigger if frame changes while cursor over image as hit test is adjusted for new image
    - Don't separately animate 2 or more controls sharing the same image. You can create a race-condition and animation frames may skip. This is because shared images animate in their shared controls. While one control is changing frames, the shared controls also may be trying to change frames. Animating one, animates all shared controls. See 'Sharing Images' above.

    Memory Usage
    -- Avoid using KeepOriginalFormat when loading images during runtime. This is a parameter in LoadPictureGDIplus
    By using that property, original image data is cached. For most cases I would think this is unnecessary. During design-time, all images are loaded with this property set to true so data can be saved in the control's property bag. Knowing this, and if you have no reason to ever extract the original data during runtime, you may wish to purge it during form load. To do so... AlphaImgCtl2.Picture.KeepOriginalFormat = False
    -- Setting KeepOriginalFormat=False still allows you to extract image data, but the format will always be PNG except for bitmaps. Format will be bitmap. This also applies to the BkgImage property
    -- The picture returned as a result of SavePictureGDIplus & MergePictureGDIplus default KeepOriginalFormat to True. You may want to reset that property after the image has been returned.
    -- Share images when possible. See notes above
    -- FastRedraw is nice to use/abuse, but only recommend using it for very large controls ( > 256x256) when special rendering is used: rotation, blending, etc, etc. On images < 256x256, rendering is generally very quick, regardless of special rendering used. When used, FastRedraw creates and maintains a separate DC and bitmap.
    -- If your TIFF, GIF, PNG, icon or cursor has multiple images (ImageCount>1) and you are only ever going to display one. Setting KeepOriginalFormat=False will not only purge the original cached data (if any), but will also convert to single frame image. Just set the ImageIndex to the one you want to use before setting KeepOriginalFormat to False.
    -- Setting WantPrePostEvents creates and maintains a separate DC and bitmap. If FastRedraw is also True, just one DC but 2 bitmaps are created.
    -- Set WantMouseEvents to false unless needed. This property determines if mouse up/down/move/enter/exit events are trapped. Mouse Enter/Exit events cause creation/destruction of timers and extra system messages. You will still get click & double click events unless the control is disabled

    Performance
    - Compile the control. The control was designed to be a separate ocx, not to be merged inside a larger project.
    - Actual-size image rendering is fastest because no scaling is required
    - Avoid special rendering styles (grayscaling, blending, transparency, mirroring, rotation, v1.1 effects, etc)
    - If you are going to use a large image always scaled at a specific size and never changed thereafter then
    a) Scale it in advance, save image to disk, and then supply that modified image instead
    b) During runtime, create a copy of the image scaled along with any special rendering styles & use it: SavePictureGDIplus function
    - If free-wheeling with scaling & rendering styles, consider using FastDraw property to speed up rendering. But see notes above regarding Animation
    - Avoid overlapping images when possible. Each image control that needs to be repainted, causes a domino effect with all overlapping image controls both above & below it in the ZOrder. This is true for all window-less controls: label, image, line & shape controls also.

    Technical Support
    - I will make changes to include bug fixes and future enhancements for some time to come
    - I will not offer support to those that have customized my code for their use. If you tweak it, you fix it
    - I will not offer suggestions on how to modify the code for personal customization. I will consider enhancement requests
    - I may offer suggestions for coding an outside routine that uses the control
    - Any enhancements may result in the control breaking binary compatibility with previous versions of the control
    - Know that the control exposes everything about the image, including the handle, effects and attributes it uses. Any enhancement I may decliine to include can be created from outside the control and implemented during Pre-Post render events. Additionally, if you can draw it to a DIB, you can load it into the control. So, you want to include an image format that isn't supported? Build a parsing routine and draw that format to a DIB, use LoadPictureGDIplus to load that DIB into the control. Want to include some filter like embossing? Get the pixels via the image handle, manipulate the pixels to another DIB, load that DIB into the control.

    Known Bugs
    - GDI+: 1 bpp PNGs may not render correctly
    - There are several other GDI+ related bugs that are handled, overridden and processed manually vs. via GDI+
    - GDI+: Not a bug. Some meta files will fail to load if GDI+ detects malicious code within the source
    - VB: When the control is added to a container that has AutoRedraw=True and the container is custom painted by you (i.e., gradients) a black line may appear at top of the container. See posts 35 & 36 below for a description & workaround.
    - VB: Whenever icons are loaded from a .Picture property or a stdPicture object, the control will report them as cursors. The GetIconInfo API is used to retrieve the icon from the handle provided by VB. That API seems to always return those handles as cursors vs. icons
    - VB: Modal windows (MsgBox, InputBox, CommonDialog, etc) can negatively affect the control while control is uncompiled. These include failed/incomplete rendering and missed events
    Last edited by LaVolpe; Dec 31st, 2011 at 01:12 PM. Reason: updated comments
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  4. #4
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control

    GDI+ used to have a bug concerning 1-BPP image:

    -- If one passes a 1-BPP ColorType=0 PNG, with say blue color background or colored chessboard background, the resulting image would have ghost lines.

    -- If one calls "GdipImageRotateFlip hImg, 6" on a 1-BPP image, the resulting image might have a thick black edge on the right side

    You mentioned that "Now enables v1.1 GDI+ Effects (file version is 6.x)"; I wonder if the bug is still there with the new version? Just curious.

  5. #5
    Junior Member
    Join Date
    Apr 1999
    Location
    Tampa, FL
    Posts
    23

    Re: [vb6]Alpha Image Control

    It's great to see this project rise from the ashes again. How different is this from the 2007 version?

    Bugwise, nothing to report, though I have not run through it thoroughly yet.

    I was just thinking up an imaginary control today where Alpha Image would play a key role. What I have in mind is a thumbnail image scroller with image fade-in and out on the edges, so as you scroll through the image list, a gradient transparency passes through the incoming and outgoing images.

    This would require a feature that would provide variable transparency across an image, and markers that would indicate where transparency began and where it would end. For example, say an image was half way into the thumbnail scroller and the transparency gradient window is 20&#37; of the image. The transparency would begin at the 30% mark, and would fade into wholly transparent at the 50% mark.

    Just a thought. Great work as always.

  6. #6

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control

    Quote Originally Posted by Jordan View Post
    It's great to see this project rise from the ashes again. How different is this from the 2007 version? ...
    Difference in this version is: written better, more flexible, more options, gets past more GDI+ "bugs"

    Regarding your fading routine. This isn't exactly what you want, but I'm sure you can adapt it.
    1) Add a picturebox to your form, set picbox ScaleMode to pixels
    2) Add an AlphaImageCtl to the picturebox, place a picture in it
    3) Change AutoSize = lvicSingleAngle. Adjust control size now so it is completely visible in picturebox
    4) Change picturebox's backcolor to any color you want or leave as is
    5) Copy and paste this code. I've included the API declarations should you not have ready access to them
    Code:
    ' declarations
    Private Declare Function GdipCreateLineBrushFromRect Lib "gdiplus" (ByRef pRect As RECTF, ByVal Color1 As Long, ByVal Color2 As Long, ByVal Mode As Long, ByVal WrapMode As Long, ByRef lineGradient As Long) As Long
    Private Declare Function GdipFillRectangle Lib "gdiplus" (ByVal graphics As Long, ByVal brush As Long, ByVal X As Single, ByVal Y As Single, ByVal nWidth As Single, ByVal nHeight As Single) As Long
    Private Declare Function GdipCreateFromHDC Lib "gdiplus" (ByVal hDC As Long, hGraphics As Long) As Long
    Private Declare Function GdipDeleteGraphics Lib "GdiPlus.dll" (ByVal mGraphics As Long) As Long
    Private Declare Function GdipDeleteBrush Lib "GdiPlus.dll" (ByVal mBrush As Long) As Long
    Private Type RECTF
        Left As Single
        Top As Single
        Width As Single
        Height As Single
    End Type
    
    Private Sub Form_Load()
          Me.ScaleMode = vbPixels
          AlphaImgCtl1.WantPrePostEvents = True
          ' don't set this during design-time. Newly discovered bug, I have to patch it this weekend
          ' Fixed bug in 30 Oct update. Can set this during design time if desired
    End Sub
    Private Sub AlphaImgCtl1_PostPaint(hDC As Long, Left As Long, Top As Long, Width As Long, Height As Long, HitTestRgn As Long)
        Dim hBrush As Long, size As RECTF, hGraphics As Long
        size.Width = AlphaImgCtl1.Width
        size.Height = AlphaImgCtl1.Height
        If GdipCreateFromHDC(hDC, hGraphics) = 0 Then
            If GdipCreateLineBrushFromRect(size, ConvertRGBtoBGRA(Picture1.BackColor, 0), ConvertRGBtoBGRA(Picture1.BackColor), 0, 0, hBrush) = 0 Then
                GdipFillRectangle hGraphics, hBrush, size.Left, size.Top, size.Width, size.Height
                GdipDeleteBrush hBrush
            End If
            GdipDeleteGraphics hGraphics
        End If
    End Sub
    Edited: FYI... The gradient fade is done overlaying a rectangle, that is filled with a gradient brush from (Color w/Alpha of zero) to (Color w/Alpha of 255). So instead of trying to fade the image into the backcolor, rather we are fading the backcolor into the image.
    Last edited by LaVolpe; Nov 14th, 2010 at 07:21 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  7. #7
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Feedback on a quick test:
    Windows platform: Vista 32-bit.

    Test scope: After adding a new project and placing the control on the new form, begin the test by loading a different graphic file in turn, via "Browse" button on Property page. No any other test conducted.

    Bugs encountered:

    (1) On PNG: For BitDepth 1 and ColorType 0 with transparency, vertical ghost lines across the resulting image at certain regular intervals (however, for BitDepth 1 and ColorType 3 one, same with transparency, it is okay).

    (2) On WMF: (a) If without "placeable" header (so-called "standard" one), resulting image appears as if "1x1" pixel size. (b) If with "placeable" header, resulting image is very much larger than it should be. Remarks: "b" results seem to vary on different tries.

    (3) On ANI: Program crashed with a 32-BPP single-group ANI.
    Last edited by petersen; Nov 1st, 2010 at 01:28 AM. Reason: Remarks: Crash is at code line "For lPtr = 1& To UBound(durSeq, 2)".

  8. #8

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Response to your quick tests
    1) Limitation of GDI+, PNGs are not processed manually; all PNGs are loaded with GDI+. I'm not going to add code to manually parse PNG files. If this is important to a user, they can load the PNG via libpng or other methods into a DIB and send the DIB to an AlphaImgCtl
    -- I do have manual routines that can read PNGs without any 3rd party DLLs. Also have routines that can write PNGs using zLIB and at better compression ratios than GDI+. Those will not be used in this project however.

    2) If you can supply one for me to play with, I can try to code around those
    b) To calculate the size of the WMF. I query the horizontal/vertical resolution the metafile was created in as reported by GDI+ and also the size reported by GDI+. The resolution and size are used in the following formula to calculate size in pixels: Size * 96 / Resolution
    If GDI+ is reporting either size or resolution differently than what you expect, then so be it; out of my control.
    The constant 96 above was used as a suggestion by you to maintain constant size regardless of user's DPI screen settings. The formula I would normally use (similar to VB) is dependent on screen DPI and looks like:
    Size * (1440 / Screen.TwipsPerPixelX) / Resolution

    3) I'll look into that, I believe I can get single-group ANI cursors from Vista in 32bpp formats. Sounds like an issue in my RIFF parsing maybe

    Thanx for the bug reports

    Edited: WMF/EMF details are not as familiar to me. I believe there are 4 types. If you post or point me to where I can get sample files like the ones you used for your tests. I can make the control more complete with regards to metafiles. Last but not least. Metafiles are scalable, for the purposes of this control, the actual size is only important if the control's AutoSize property is used and the Aspect property is ActualSize, otherwise, the actual size of any loaded image is irrelevant with regards to the scope of this control.
    Last edited by LaVolpe; Nov 7th, 2010 at 01:45 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  9. #9
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    I attach two WMF files as requested - one with "placeable" header and one without. A 32-BPP ANI is also included for your ready use.

    I myself do not have much knowledge on EMF/WMF, but just enough to handle them (load and save). In view of the lacking of published materials, the following are pertinent to getting a grip of WMF.

    I would say WMF is a mess (like many things coming out from MS, e.g. look at ICO header and look at Resource file structure for Cursor versus that for Icon, the original design was so loose). As a result, we got 4 types of it as you said (I would say 5 actually, the 5th one being of a "bitmap" variation rather than GDI commands).

    With a "standard" WMF file, what you get from calling GDI+ is basically your screen size. Therefore, it was fully justifiable for Aldus to add a placeable header, in order to establish the intended image size with certainty.

    ' "Standard" metafile. 18 bytes.
    Private Type METAHEADER
    mtType As Integer
    mtHeaderSize As Integer
    mtVersion As Integer
    mtSize As Long ' Value of mtSize needs to be "x2", as it is in Words
    mtNoObjects As Integer
    mtMaxRecord As Long
    mtNoParameters As Integer
    End Type

    ' "Aldus Placeable" header
    Private Type PLACEABLE
    Key As Long
    handle As Integer
    Left As Integer
    TOp As Integer
    Right As Integer
    bottom As Integer
    Inch As Integer
    Reserved As Long
    Checksum As Integer
    End Type

    It is because of what is said in the previous paragraph, you will notice that the image returned from your Icon Resource Organizer is distorted, if you load the one without placeable header. For a comparison, you can download a gadget of mine to try the same (where the size is halved intentionally), Like you I am an amateur graphics lover, as such there might be some other materials of referecne value to you in the said gadget. Just unzip it to a temp folder (there are 2 DLLs there, dispensing any or all of them would not affect the program running). (Will remove URL a bit later today).

    An explanation of "* 96/120" is in order. On one hand, pixels are a device dependant scalemode, on the other hand, himetric is based on the metric system which is device independent. Therefore, in order to arrive at the same pixel units irrespective of the DPI settings, we have to take into account of the DPI value in converting HiMetric to Pixel.

    This morning I purposely powered off and on of my PC and I am able to re-produce all of what I said in my previous posting. However, there is one point I want to bring to your attention: The test results of "a" and "b" of "2" in my previous posting seem to vary on different tries, much depends on what has been loaded previously.
    Attached Files Attached Files
    Last edited by petersen; Nov 5th, 2010 at 09:50 AM. Reason: Corrected an ugly typo of the word "halved"

  10. #10

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Thanx for the info. Will be playing with this today/tonight. Already figured out the ani problem; If/Else logic error failed to size an array (easy fix). Will now work on the metafiles & post results & update project later.

    Initial look at the 2 WMFs you gave me. More research needed by me, not looking promising...
    Placeable: 1.135 width:height ratio, using a 1000 v/h resolution
    NonPlaceable: 1.56 width:height ratio and GDI+ converts to EMF using 93.78 v/h resolution
    Last edited by LaVolpe; Nov 1st, 2010 at 11:29 AM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  11. #11
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Re: For NonPlaceable, just a reminder -- see 4th ("With a "standard" WMF file ....) and 5th paragraphs of my previous posting.

  12. #12

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Gotcha. Decisions, decisions. The only way I'll know if the WMF is not placeable is to parse the header info (and not opposed to doing it)
    I see where a default of 1/2 size could be useful or even using 1/8. What I see as a potential issue is the screen size. The width/height ratio of the non-placeable WMF will be same as the screen width/height ratio; therefore, giving a stretched vs scaled appearance. This is because non-placeable header's don't include image dimensions; therefore, the intended width/height ratio cannot be known.
    Last edited by LaVolpe; Nov 1st, 2010 at 01:24 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  13. #13
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Another reminder:

    What is said in the last sentence of the last paragraph of my posting #9 is in fact a bug which you may want to address. I would have it included as:

    (4) On general: .....

    in my posting #7 if I knew it at that time.

  14. #14

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Quote Originally Posted by petersen View Post
    Another reminder:

    What is said in the last sentence of the last paragraph of my posting #9 is in fact a bug which you may want to address. I would have it included as:

    (4) On general: .....

    in my posting #7 if I knew it at that time.
    Not sure I understand. Keep this in mind. During design-time...
    1) If control has no picture assigned, any new picture will be shown actual size.
    2) If control had picture, the replacement picture will be scaled to the control dimensions dependent on the Stretch property.

    I am not exactly happy with that functionality and may revert to how VB does it: If Aspect=ActualSize, load image actual size else scale to Aspect property's setting. Still thinking on this. One thing I always disliked about VB is that loading a image into a VB image control during runtime, resized the image control unless Stretch=False.

    Edited: Changed behavior
    Design time: If Aspect=ActualSize, control will be resized to show entire image, regardless of AutoSize
    Run time: The AutoSize & Aspect are honored. In same situation: Aspect=Actual Size and AutoSize=NoAutosize then image may be clipped if control is not big enough to display entire image.
    Changes made to imitate VB's Image Control behavior during design time. Note that VB's Image Control has only 2 settings: Stretch=False sizes control to image's dimensions. Stretch=True sizes image to control's dimensions.
    Last edited by LaVolpe; Nov 7th, 2010 at 01:46 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  15. #15
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Regarding VB Image control, I generally leave the default as it is, unless I see there is a need (in rare occasions I do feel the need to change the default Stretch property).

    In the current case, somehow a practical arrangement should be made, e.g. there is no reason that when the user loads the first picture, the size is automatically fit to the originally coded size, wnen he/she loads a smaller one then the size no longer fits -- not every user is like you and me knowing why and how.
    Last edited by petersen; Nov 1st, 2010 at 03:05 PM.

  16. #16
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    It appears to me that it would be nice if user can effect the settings you mentioned right on the Property screen as well (if this doesn't involve much coding overhead).

  17. #17

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Quote Originally Posted by petersen View Post
    It appears to me that it would be nice if user can effect the settings you mentioned right on the Property screen as well (if this doesn't involve much coding overhead).
    I'll take it into consideration. Look for control updates a bit later tonight to address wmf & ani cursor issues.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  18. #18
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    This one is just for reference, whilst we are here.

    I didn't test any animated GIF file so far (because I stopped my quick test when I bumped into "(3)" mentioned in my posting #7), so I've this evening made a few more clicks, specifically on animated GIF files, to complete the job.

    I now upload a zip containing an animated GIF file, somewhat tricky and interesting. The Image control cannot animate it correctly, but neither can FireFox/IrfanView. However, on the other hand, Internet Explorer animates it perfectly right (my own programs also).
    Last edited by petersen; Nov 7th, 2010 at 12:53 AM.

  19. #19
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Bug report.

    A guy sent me a few animated GIF files (to ask some questions), one of them appears interesting to me because it somewhat resembles the above-said one in the arrangement of disposal methods used (but instead of To Background, To Previous). So I fetched your new copy to try this one on it.

    As the frame displays do not appear alright, so I come back to report this one. Unlike the file in my early posting, which a different browser/program may have a different practice to handle (that is why I didn't call it a bug), this one is certain (as the practice of all browsers/programs should be the same, so I call it a bug)..

    Shown below is one of the animation frames - in the running rabbit place, one can see a rectangular area with distorted/lightened colors.

    Zip containing the source GIF file is attached, hope it helps.
    Attached Images Attached Images  
    Last edited by petersen; Nov 7th, 2010 at 12:54 AM.

  20. #20

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Yep, you've discovered another GDI+ bug apparently or something wrong with my code.
    I don't think it's my code simply because I'm asking GDI+ to move to the next frame and then render what it gives me. I'll look into it a bit further. Maybe something to play with this weekend.

    BTW: I ran your GIF in my personal animated GIF app (one I wrote) and it ran correctly. Agreed, no disposal code issues here.

    Edited: I've got dozens upon dozens of GIFs (some badly coded) that I've collected when I wanted to learn the GIF format. I think I'll spend some time on this to see how many of those GDI+ failed to render correctly. I'd sure hate to have to supply my own GIF routines since GDI+ makes it sooooo easy. But if this is a bigger problem, then I may go that route.

    Follow up: Frame disposal codes are: 1,3,3,3,3. The 1st 2 frames draw good; then bad after that. Now to look at other GIFs with multiple 3s placed consecutively. I may have to quick parse GIFs to determine disposal codes & decide whether or not to use GDI+ or manual rendering. Again, something to play with this weekend.

    Edited: Another follow-up. Using v1.1 of GDI+ resulted in the same improper rendering.
    Last edited by LaVolpe; Nov 7th, 2010 at 11:33 AM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  21. #21
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Edited: I've got dozens upon dozens of GIFs (some badly coded) that I've collected when I wanted to learn the GIF format ......
    I got the impression (from past discussions) that you honestly adhere to what is stated in MS documentation / format specifications, which is good and necessary. Unfortunately I found that often some judicial adjustment is necessary here and there. Take GIFs for example (since we are talking of GIFs), I used to be serious to conduct a preliminary validation of the incoming file and would reject a file without a GIF trailer. However, if other programs accept such a file (they do), then my clients might think it is something wrong with my program. So, I have to relax that check (forget the laid down specification). Just a mention.

  22. #22

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Well, with my personal GIF routines, I've relaxed some things too. But I won't work around a poorly coded GIF and allow well-coded/formatted ones to suffer.

    Anyway. I think I've discovered what's different in your GIF and why GDI+ may have failed. I'll look more into it later: local color table usage vs. global color tables. I know this is a bug regarding saving GIFs; didn't realize it may be a bug displaying them. Will be tweaking some code so I can scan 100's of files, looking for ones with local color table usage. Consecutive code 3s isn't the problem, I've a few of those and they rendered fine with GDI+. Almost seems as if more than one local color table, it is an issue. I've found a couple of mine that have 1 local color table and it came out ok. Your gif has 4 local color tables starting with frame #2.

    Edited: Follow-up. I searched over 5,000 gifs & could not find another one like yours. I did find many that used multiple local tables and all rendered ok. So I'm assuming the GDI+ bug comes in this category: multiple local tables and disposal code of 3. All the ones with multiple color tables I have have disposal codes of 1 or 2, not 3. I'm chalking this up to out of my control for now. Manually processing/displaying GIFs to handle a rare occurrence isn't a priority for me.
    Last edited by LaVolpe; Nov 7th, 2010 at 01:22 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  23. #23
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    You mentioned the use of local palettes, so I took a look at them and I don't like them in the original file uploaded in the earlier posting. They all use 256-color tables whereas each frame has not more than 8 colors.

    I've now tidied up/simplified the said tables, so that each table does not contain more than 8 colors. The result is a reduction of the file size from 13,523 to 10,189 bytes. Just for a bit of fun only.
    Attached Files Attached Files

  24. #24

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    That is one advantage of GIF. A table can be any bit depth between 1 and 8, so your table doesn't have to be a size typical with bitmaps, it can be: 2, 4, 8, 16, 32, 64, 128, 256

    Also, if you are playing with your own GIF writer, I doubt all 4 tables are different. It might be better to use a global table for the last 4 frames and a local table for the first frame. The GIF will be smaller yet. In fact, GDI+ may even display it properly then too

    Edited: I wrote a GIF writer awhile back. I actually took the time to optimize the color tables per frame. If all colors could be squeezed into one table then one table used. Otherwise, it would create a table that a majority of the frames would use and set that one as global. The odd-ball frames would then have their own color tables as needed. This logic reduced GIF size very well. But a majority of GIFs out there are based on a single table and those can be optimized many times also. Example like yours: 256 palette, but far less colors used.
    Last edited by LaVolpe; Nov 5th, 2010 at 09:08 AM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  25. #25
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    That rabbit GIF file which the guy sent me is from some site on the web. As it is supposedly a professional site, hence I am a bit surprised when I find such a sloppy palette table building.

    Actually, although we can limit the entries in a table to any number between 1 and 256, in VB6 world steps of 1, 4 and 8-BPP still have to be observed in the actual table size. There are constraints set by stuff like BITMAPINFOHEADER and GetDIBits.

    We may have a 2-BPP PNG file (really coded 2-BPP), but when we process such a file, it is dealt with on a 4-BPP basis because of the above-said. Also VB6 cannot directly handle some camera raw files which are often 48-BPP, not to say the 96-BPP and 128-BPP High Dynamic Range images such as HDR & EXR (C++ guys often deal with BPPs not usually seen in VB6).

    Nevertheless, for our purposes, VB6 is good enough to cover the commonly used images perfectly alright.

  26. #26

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Quote Originally Posted by petersen View Post
    ...Actually, although we can limit the entries in a table to any number between 1 and 256, in VB6 world steps of 1, 4 and 8-BPP still have to be observed in the actual table size. There are constraints set by stuff like BITMAPINFOHEADER and GetDIBits.
    Not really. The bitmap/dib table size is restricted, but not the GIF table size, other than what I mentioned earlier. The two have no direct relationship. If the GIF table size is 6 bits, then supply an 8 bit dib table and fill in just 64 of 256 dib colors. And if converting dib to GIF, simply keep track of how many color are used, if just 64, then GIF color table should be 6 bit, not 8 bit IMO.
    Last edited by LaVolpe; Nov 5th, 2010 at 10:47 AM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  27. #27
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    You can save at 3 * (2 ^ BPP) in file alright, what I am talking about is whenever we process the image it is still on 1, 4 & 8-BPP basis, due to what is limited by BITMAPINFOHEADER and GetDIBits. This is analogous to 2-BPP PNG case -- file size is smaller than 4-BPP, but requiring some overhead in handling. Of course GIF is always 8-BPP. Anyway, I do allow users to move up or down in steps of (2 ^ BPP) in my Animated GIF Editor. I believe the redone tables in the "rabbit" file reflects that essence.
    Last edited by petersen; Nov 5th, 2010 at 11:51 AM. Reason: Corrected a couple of typos in BPP thing

  28. #28
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Just a reminder. Some images can be big, e.g. TIFF and camera JPG are notoriously so, hence you might want to set an allowable max to the Image control size.

  29. #29

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Quote Originally Posted by petersen View Post
    Just a reminder. Some images can be big, e.g. TIFF and camera JPG are notoriously so, hence you might want to set an allowable max to the Image control size.
    Worth thinking about... I was considering maxing it out at control's container size, but haven't decided how I wanted to implement it. VB will limit a control's size but that size can still be absolutely huge.
    Code:
        UserControl11.Width = Screen.Width * 1000
        UserControl11.Height = Screen.Height * 1000
        
        Debug.Print "Widths - screen/control: "; Screen.Width \ Screen.TwipsPerPixelX; UserControl11.Width \ Screen.TwipsPerPixelX
        Debug.Print "Heights - screen/control: "; Screen.Height \ Screen.TwipsPerPixelY; UserControl11.Height \ Screen.TwipsPerPixelY
    Edited: Would be nice of me to post the results, huh
    Widths - screen/control: 1920 16383
    Heights - screen/control: 1200 16383

    And another thing to consider. If control size is adjusted by me because "it is too big"; that will have an effect on how the image is rendered within the control if the Aspect setting is not ActualSize or FixedSize. Thinking....

    Edited yet again. After playing around with this, I am going to restrict maximum control size to the screen size (in pixels of course)
    Side note: The O/S has a max DIB size that is not documented, but a max size nonetheless. Since AutoRedraw obviously uses an offscreen DIB to cache the rendered state of the image, a large image may outsize the O/S max. If that is the case, the O/S will simply fail to create the DIB requested. This error check has been in-place since the beginning: If O/S fails to create DIB then AutoRedraw is reset to False.
    Last edited by LaVolpe; Nov 7th, 2010 at 01:47 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  30. #30
    Hyperactive Member
    Join Date
    Jul 2010
    Posts
    273

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Just for info.

    (i) For the earlier attached GIF file, you suspect that the incorrect animation on Image control has something to do with local palettes, I can confirm that it doesn't -- I put all frames to a global palette and the problem remains.

    (ii) For years there had not been once that the earlier mentioned "to background" file failed to show alright on IE7, until today. I guess MS has meanwhile dumped something to my machine, kind of "auto-update" thing (despite I had already turned off auto-update), because when I re-test it again now, IE7 no longer shows it alright (scary, as if MS is ear dropping our conversation). it remains alright on IE6 though, because that machine is not connected to web. Because of this I have now revised my main program a little and removed the option to show animation in the manner as in IE.

    (iii) In my programs, there are 4 options to show individual frames, against program's screen color, at frame's own transparent color if any, on a chessboard, and at frame's net size (for those less than background size). There is also a summary of frames data. If you are interested in one of my programs as a kind of 2nd reference when you test your GIF files, you can fetch a gadget at ...... (I will remove URL a bit later). I have animated GIF submenu included in this gadget because a couple of years ago I had encountered an animated GIF file with over 1600 frames.
    Last edited by petersen; Nov 8th, 2010 at 10:12 AM. Reason: Removed URL as originally intended

  31. #31

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Appreciate the offer. I have my own GIF parsing/rendering routines and I am 100&#37; confident they are written correctly. As far as making assumptions about GDI+ and local color tables? That's all I can do, I don't know what methods it uses internally to do the job. Obviously it appears broken in this case.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  32. #32
    Junior Member
    Join Date
    Feb 2008
    Posts
    20

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Hi LaVolpe!

    Love the control, thank you for continuing to update it.

    I seemed to have run into what may be a bug or glitch with the control. When I create a usercontrol, place your control on there and then create a function for drawing a line, I get a black line at the top of the control. It's quite weird. As soon as I remove your control it stops happening.


    (Notice the black line at the top?)

    Any ideas?

    Please see attached project for example of glitch/bug or code below to replicate.

    Code:
    Private Sub UserControl_Initialize()
    
        Call Draw
    
    End Sub
    Private Sub Draw()
    
        With UserControl
            .Cls
            Line (0, 0)-(0, .ScaleHeight), vbBlue
        End With
        
    End Sub
    
    Private Sub UserControl_Resize()
    
        Call Draw
        
    End Sub
    Tested on two different Win7 x64 machines.
    Attached Files Attached Files
    Last edited by Stidor; Nov 14th, 2010 at 06:31 PM. Reason: Adding attachment

  33. #33

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Yes, it is a common bug with VB usercontrols. There is a workaround.
    For others, this is the scenario.
    1) Place AlphaImgCtrl in a picturebox. Set the picturebox AutoRedraw=True
    2) Draw custom graphics to the picturebox, like a gradient background for example
    3) Solid black line appears at top of the picturebox

    BTW, it appears with all VB usercontrols where properties: Windowless=True & BackStyle=Transparent and the container's AutoRedraw=True

    The fix: After you draw your background, then call: Set Picture1.Picture = Picture1.Image

    Edited: You are adding my control to another usercontrol. Same principle should apply:
    Set UserControl.Picture = UserControl.Image
    Last edited by LaVolpe; Nov 14th, 2010 at 07:07 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  34. #34
    Junior Member
    Join Date
    Feb 2008
    Posts
    20

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Ah I see. Thanks LaVolpe, first time I've come across it.

    Will give your fix a test tonight, much appreciated.

  35. #35

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    You're welcome. I only came to know this bug a couple years ago myself.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  36. #36
    Junior Member
    Join Date
    Feb 2008
    Posts
    20

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Worked perfectly. Thanks again. :-)

    What I'm planning (or rather hoping) is to replace my current image/picturebox control in my custom button. However I'm thinking this may not work. Will I be able to load in alpha images (pngs) into my custom button control's picture property during design time? Or am I going to have to load them from an external resource at run time?

    I guess the better question is, does VB6 handle storing alpha images in control picture properties, and can this control load images from the property store?
    Last edited by Stidor; Nov 15th, 2010 at 04:29 AM.

  37. #37

    Thread Starter
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    You will want to create a property page, similar to the one I use for the alpha image control. That property page will allow users to select non-vb supported file formats (i.e., png, tif, tga). You can then feed the file to the AlphaImgCtl within your 'button'. To save the content of the file, store the file contents in a byte array. Save the byte array to your property bag during WriteProperties event. During ReadProperties, load the array from your propertybag and feed it to the AlphaImgCtl. You may want to look at how I do that in my control's Read/WriteProperties events

    Another option, not very user friendly is to have them copy & paste the file path/name in a String public property and then load the file content from that.

    Obviously you can't do this the easy way with a stdPicture object because user's will not be able to select non-vb supported image formats.

    Edited. Give me a few minutes & I'll post a simple example and workaround for you. It's easier than it appears.
    Ok, here we go....
    1) In your usercontrol project, add a property page. Give it a more meaningful name as needed vs. PropertyPage1
    2) Bring your usercontrol into design view. Find PropertyPages in the property sheet
    3) Click the ellipse button (...) and select your new property page. Then close that window
    4) Within the property page, simply add a button and leave it named command1 for this simple example
    5) Also add 1 timer to the property page and leave its default settings
    6) Copy & paste this code into the property page
    Code:
    Option Explicit
    
    Dim cBrowser As UnicodeFileDialog
    Dim cImage As GDIpImage
    
    Private Declare Function GetParent Lib "user32" _
      (ByVal hwnd As Long) As Long
    
    Private Declare Function SetWindowPos Lib "user32" _
      (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, _
      ByVal x As Long, ByVal y As Long, ByVal cx As Long, _
      ByVal cy As Long, ByVal wFlags As Long) As Long
    
    Private Declare Function PostMessage Lib "user32" Alias _
      "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, _
      ByVal wParam As Long, ByVal lParam As Long) As Long
    
    Private Const HWND_TOP = 0
    Private Const SWP_NOSIZE = &H1
    Private Const SWP_HIDEWINDOW = &H80
    Private Const WM_CLOSE = &H10
    
    Dim hwndPP As Long
    
    Private Sub PropertyPage_Paint()
       Dim lresult As Long
       lresult = GetParent(PropertyPage.hwnd)   ' Work back to the
       hwndPP = GetParent(lresult)              ' dialog window.
       lresult = SetWindowPos(hwndPP, HWND_TOP, 200&, 200&, &O0, &O0, _
          SWP_HIDEWINDOW Or SWP_NOSIZE)
    End Sub
    
    Private Sub Timer1_Timer()
       Dim lRet As Long
       Timer1.Enabled = False     ' You will not need the Timer again.
       Command1.Value = True      ' Click the CommandButton.
       If PropertyPage.Changed Then PropertyPage_ApplyChanges  ' Apply the new settings.
       lRet = PostMessage(hwndPP, WM_CLOSE, 0, 0) ' Close the dialog box.
    End Sub
    
    Private Sub Command1_Click()
        If cBrowser.ShowOpen(PropertyPage.hwnd) Then
            On Error Resume Next
            Set cImage = LoadPictureGDIplus(cBrowser.FileName, , True)
            If Err Then
                Beep ' image failed to load
            Else
                PropertyPage.Changed = True
            End If
        End If
    End Sub
    
    Private Sub PropertyPage_ApplyChanges()
        Dim bData() As Byte
        cImage.ExtractImageData bData
        PropertyPage.SelectedControls(0).Image = bData()
        PropertyPage.Changed = False
    End Sub
    
    Private Sub PropertyPage_Initialize()
        
        Set cBrowser = New UnicodeFileDialog
        With cBrowser
            .Filter = "All Files|*.*|" & _
                "Supported Formats|*.bmp;*.cur;*.ani;*.gif;*.ico;*.jpg;*.jpeg;*.emf;*.wmf;*.mp3;*.png;*.apng;*.tga;*.tif;*.tiff|" & _
                "Bitmap|*.bmp|Cursor|*.cur;*.ani|GIF|*.gif|Icon|*.ico|JPEG|*.jpg;*.jpeg|" & _
                "Metafile|*.emf;*.wmf|MP3|*.mp3|PNG|*.png;*.apng|Targa (TGA)|*.tga|TIFF|*.tif;*.tiff"
            .FilterIndex = 2
            .Flags = OFN_EXPLORER Or OFN_FILEMUSTEXIST
            .DialogTitle = "Select Image"
        End With
        Timer1.Enabled = False
        Timer1.Interval = 1
    
    End Sub
    
    Private Sub PropertyPage_SelectionChanged()
        PropertyPage.Changed = False
    End Sub
    7) You'll need a way to have the property page talk to your usercontrol to get/set properties. In this example, create a new property called image and copy/paste the relevant code from what I posted here:
    Code:
    Public Property Let Image(newValue As Variant)
        ' Write-only property
        On Error Resume Next
        Set AlphaImgCtl1.Picture = LoadPictureGDIplus(newValue)
        If Err Then
            ' probably should raise an Err here. Failed to load image
        Else
            ' refresh your control. New image was applied
            PropertyChanged "Image"
        End If
    End Property
    
    Private Sub UserControl_ReadProperties(PropBag As PropertyBag)
        Dim bData() As Byte
        bData() = PropBag.ReadProperty("Image", bData())
        On Error Resume Next
        Set AlphaImgCtl1.Picture = LoadPictureGDIplus(bData())
        If Err Then Err.Clear
        On Error GoTo 0
        ' read any other properties
    End Sub
    
    Private Sub UserControl_WriteProperties(PropBag As PropertyBag)
        Dim bData() As Byte
        If AlphaImgCtl1.Picture.ExtractImageData(bData) Then
            PropBag.WriteProperty "Image", bData()
        End If
        ' write any other properties
    End Sub
    Note that the Image property above is for the example. You may want to change the property name or write your own. Whatever you decide upon, remember to make the appropriate change in the property page that calls it to get/set image data. The property does not need to be Public, but if not, other tweaks need to be made.

    The hack to show the open file dialog window instead of the property page is described in this MSDN article. So if you actually want to design a property page to allow users to change other properties of the control, remove the timer-related code. This MSDN-suggested hack is only recommended if all you do is want to display a dialog box.

    If you are new to property pages, they are not that difficult to use. Here is a great reference to assist if needed (in pdf format)

    Last but not least. If you don't compile my control, you may get a registration error when trying to compile your control.
    Last edited by LaVolpe; Nov 15th, 2010 at 01:17 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  38. #38
    Junior Member
    Join Date
    Feb 2008
    Posts
    20

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more)

    Fantastic post LaVolpe, you've made it seem quite easy. Can't wait to give it a go when I get home from work this evening. I've never had a need to play with Property Pages so this should be a great learning exercise.

    Thank you for the explanation and example code, much much appreciated.

  39. #39
    New Member
    Join Date
    Oct 2011
    Posts
    10

    Re: [vb6]Alpha Image Control (PNG, AniGIFs, TIFF, & more) [20 Oct 2011]

    Hallo Master,

    Could you fix the HitTest problem please?
    I want to use this control as a custom shape button, but the HitTest is not working correctly.

    ps: I've been using your AlphaImageControl.ocx (v1.0) for my projects. THANK YOU!

  40. #40
    New Member
    Join Date
    Sep 2012
    Posts
    4

    Smile Re: [vb6]Alpha Image Control v2 - Final Update (15 Jan 2012)

    hi, i have this LavolpeAlphaImage2 activeX control. what i want is to load a picture in it via common dialog during runtime. how can i possibly do this. kindly show me an example. thanks in advance

Page 1 of 18 123411 ... LastLast

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width