Using VBA to insert and keep images in file - Excel 2013 - image

I'm working on a macro for a friend of mine who needs to import a set of images in an excel document and later use this document on other computers. The problem I encountered is that when opening this document on a different computer, all the images are gone and instead you get these little error signs, indicating that the image path could not be found.
I have developed the macro on my own computer where I have Excel 2007 and for me, the code works perfectly fine. My friend uses Excel 2013 and apparently, there seems to be a major difference on how those 2 versions deal with the image importing and saving.
Overall, I found 2 different ways how to insert images. The first one I tried was something similar to this:
Set pic = ActiveSheet.Pictures.Insert("C:\documents\somepicture.jpg")
The second way of doing this looked like this:
Set pic = Application.ActiveSheet.Shapes.AddPicture("C:\documents\somepicture.jpg", False, True, 1, 1, 1, 1)
In the documentation for this 2nd approach it is said that the 3rd paramenter (which is True here) is responsible for saving the picture with the document.
However, both these approaches look more or less the same in the end result: They work fine for me but won't work if they are executed on my friends pc with Excel 2013. So what I need is a work-around for the newer Excel versions (I read somewhere that from Excel 2010 upwards, there is a bug or something like that with these image import methods).

In all my uses, Adding a picture with Insert makes a reference to a file on your harddrive, for whatever reason if you want the image to be embedded in the file you have to add a shape and then put the image on the shape using the AddPicture (like you use), I have never had any issues with this.
Also you are giving the picture a height and width of 1 pixel, You will almost never be able to see that true setting that higher as below:
Application.ActiveSheet.Shapes.AddPicture "C:\documents\somepicture.jpg", False, True, 1, 1, 100, 100
I have a feeling it was working all along and you just never saw the picture cause it was too small.

The first snippet works just fine, but it does not allow picture positioning (i.e. if you need a pic placed at some certain range), so I made something that works nicely with positioning available, based on the second solution, such as it is shown below.
Dim r As Range
Dim pic As Shape
Set r = ActiveSheet.Range("A34:Q58")
Set pic = ActiveSheet.Shapes.AddPicture(ThisWorkbook.Path & "\FracAnalysis.png", _
linktofile:=msoFalse, savewithdocument:=msoCTrue, Left:=0, Top:=0, Width:=-1, Height:=-1)
With pic
.LockAspectRatio = msoFalse
.Top = r.Top
.Left = r.Left
.Width = r.Width
.Height = r.Height
End with

Previous answer has been really useful! I just wanted to add the reference to the method parameters (I thought the width and height were in pixels, turns out they're in points):
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.shapes.addpicture.ASPX

I usually run a macro that downloads images from a server into files that are then forwarded to clients who do not have access to that server. My coding is quite basic so I'll just copy the particular line I use to insert the picture:
Set pic = ActiveSheet.Shapes.AddPicture(Filename:="C:\documents\somepicture.jpg", _
linktofile:=msoFalse, savewithdocument:=msoCTrue, Left:=0, Top:=0, Width:=-1, Height:=-1)
I know its technically the same code as the one you proposed, but try using msoCTrue and msoFalse. I seem to recall that being part of the issues. Let me know if it works and maybe we can try something else. It works for me, so we should be able to get it to work for you.

Related

Using ABCPDF draw another doc as an image with rounded corners

I find ABCPDF is very capable. However, so far I had not managed to find a way to draw one PDF into another with rounded corners - until now. But, the approach I discovered depends on getting the correct PDF object id for the inserted PDF stream, and herein lies the reason for this question.
Anyone who knows ABCPDF will ask why that is an issue ? Does not the addImageDoc() function which embeds one PDF inside another return the PDF object ID ? No - it returns something else - most likely the inserted PDF goes into the document catalogue as an isolated object and what you get in the returned ID is an object that refers to it. Unpacking the document streams seems to bear this out.
Long story short, in my experimenting I found that I needed to insert into the stream a 'Do' call, with the target of that derived as:
imgObjId = addImageDoc(some pdf object) // inserted off-page
insert into stream "/Iabc<imgObjId + 1> Do"
For example, if the returned imgObjId value is 5 then I need it to be 6 to make
/Iabc6 Do
Question: Whilst this works OK, I am relying on adding one to the returned value and I wonder how robust that is going to be. Or is there a correct way to achieve this ?
More info: I have kept the question short but readers may be wondering why the above matters? Because to achieve rounded corners you need to construct a stream of PDF commands which has a clipping region defined. Think of a path for a rectangle with Bezier curves for the corners. Having got that, you need to draw an image, or in my case another PDF, into the same context so as to get the clipping effect. After that you can close and reset the graphics state and be a good PDF stack citizen. However, there is no means, other than my approach above, that I can find in ABCPDF to get a handle on the inserted PDF doc stream in the catalogue so as to be able to ask for it to be drawn somewhere else.
Inserting an image seems to be a similar process, except the getinfo() function can discover the pixmap. There appears to be no like approach for an embedded PDF.
I don't know if you can change the target abcpdf rectangle prior to do a "AddImageDoc".
Maybe you can do a trick, getting a Bitmap from the source, editing it by changing borders, and adding to a new doc. Something like this:
Dim oDoc As New WebSupergoo.ABCpdf10.Doc
Dim oImg As System.Drawing.Bitmap
oDoc.Read("D:\source.pdf")
oImg = oDoc.Rendering.GetBitmap()
' image quality can be improved with .Rendering properties as 'AntiAliasImages', etc.
oDoc.Dispose()
oDoc = Nothing
Dim oGraph As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(oImg)
Dim gPath As New System.Drawing.Drawing2D.GraphicsPath
Dim oBrush As New System.Drawing.SolidBrush(System.Drawing.Color.Red) ' only to see the rectangle... white when be ready
gPath.AddRectangle(New System.Drawing.Rectangle(0, 0, oImg.Width, oImg.Height))
' 2 / 100 it's the percent factor for borders
Dim iLeftBorder As Integer = CInt(2 / 100 * (oImg.Width / 2))
Dim iTopBorder As Integer = CInt(2 / 100 * (oImg.Height / 2))
gPath.AddEllipse(New System.Drawing.Rectangle(iLeftBorder, iTopBorder, oImg.Width - (iLeftBorder * 2) - 1, oImg.Height - (iTopBorder * 2) - 1))
oGraph.FillPath(oBrush, gPath)
oBrush.Dispose()
oGraph.Dispose()
oDoc = New WebSupergoo.ABCpdf10.Doc
oDoc.AddImageBitmap(oImg, False)
oDoc.Save("D:\finalpath.pdf")
oDoc.Dispose()
oDoc = Nothing
But it's only a "trick".

Scale / Resize StdPicture in VB6

I have looked far and wide and reached the end of my wits trying to figure out how to do this. I have looked on XtremeVBTalk.com and the rest of the internet on how to resize a damn StdPicture!
Does anyone know how to do this? Is this even possible?
Thank you so much in advance. I desire not to use any type libraries etc. so if that is offered in a solution I don't think I will be able to use it.
I'm not using A picturebox control at all.
Say I have the following function header, and an StdPicture is passed in:
Private Function EncodeImageToBase64(ByRef Image As StdPicture) As String
I then have the following declarations where I intend on encoding the StdPicture to base64:
Dim xmlDoc As DOMDocument60
Dim xmlNode As MSXML2.IXMLDOMElement
Dim bColor() As Byte
Dim bMask() As Byte
Dim bImage() As Byte
Dim lCrcTable() As Long
Dim lWidth As Long
Dim lHeight As Long
EncodeImageToBase64 = vbNullString
If Image Is Nothing Then
Exit Function
End If
Call CRCTable(lCrcTable)
Call Icon2Arrays(Image, bColor, bMask, lWidth, lHeight)
If Not CreatePngByteArray(bImage, lWidth, lHeight, bColor, bMask, lCrcTable) Then
Debug.Assert False
Exit Function
End If
However, before calling that, I want to cut the image's width and height in half. How can I do so? CreatePngByteArray only supports 16x16 PNGs and I am using 32x32, so I'd like to cut them down in order to pass the asserts they have.
OK, I spent quite some time that I didn't really have on this one, because I didn't know the answer to begin with, but I was still interested in finding out what the potential solution was.
The following answer is my understanding of what you are trying to do, but may not be the answer to the question itself, so it could very well be considered wrong.
So, here's what I came up with. You will need to use an IPictureDisp object instead of an StdPicture object. You will also need to use a PictureBox control, even if you don't really want to.
Create a new project. Add a form, or open an existing one if one is provided. Set the ScaleMode of the form to pixels. Add a PictureBox control on the form. Set the AutoRedraw property of the PictureBox control to 'True', the BorderStyle property of the control to 'None', and the Height and Width properties of the control to 16 pixels each. Add the following code to the form, and modify the location and type of the image that you want to resize, and then the location to save it to:
Private Sub Form_Load()
Dim TestPic As IPictureDisp
Set TestPic = LoadPicture("C:\Users\Your Name\Desktop\image.gif")
With TestPic
.Render Picture1.hDC, 0, 16, 16, -17, 0, 0, .width, .height, 0
End With
SavePicture Picture1.Image, "C:\Users\Your Name\Desktop\image2.bmp"
End Sub
The image can start with any of the types that Visual Basic 6 supports (.bmp, .cur, .gif, .ico, .jpeg or .jpg, and .wmf), but must always be saved in bitmap format. Please note that Visual Basic 6 does not support PNG file formats at all, so you will not be able to use any VB6 functions to open PNG files or create them.
I would be interested in other solutions that other people come up with.
Edit: Fixed dimensions.
Do you mean inside the PICTUREBOX control or inside an IMAGE CONTROL? Because If I remember correctly it has a STRETCH property which autofits the image to the container
#Zaf Khan beat me to it. I have something similar where I have a PictureBox. Under behaviour I have SizeMode set to StretchImage then when I load an image like so
LoadWebImageToPictureBox(ImagePreview, SelectedFile)
it auto fits.

Load Picture to Microsoft Access 2010 Ribbon from Table

I'm working with Access 2010's new ribbon feature, and I'm trying to figure out the simplest way to load an image to the ribbon from a table. I know that I could do this by using a GDI API function, but from what I can see the code looks convoluted and appears to utilize extra dlls that I would just as well avoid calling if I don't need to. I also know that I could create a control on a form, load the image to the form, and then load the image from the form to the ribbon image variable. While using the form is doable, it seems sloppy. Eventually, I will resort to one of the two preceding methods if I have to, but it just seems like there should be some simple way to load an image from a table directly into an image variable for the ribbon.
One thing to note is that I'm willing to use whatever image format is easiest. These icon files are very small and so I'm not concerned about file size and I also don't care whether or not they are capable of transparency. So if there's a method that only works with bitmap file types that is fine with me.
Here's the code I have for the button in the ribbon XML:
<button id="CCTrans" label="Credit Card Trans." getImage="GetMnuIcn" onAction="=OpenCCTrans()" />
And here's the code I have for retrieving the image:
Sub GetMnuIcn(control As IRibbonControl, ByRef Image)
Set Image = DLookup("Img", "LtblImg", "Lbl=""" & control.ID & """")
End Sub
I've tried storing the image both as an OLE Object and as an attachment. Either way, when I try to retrieve it, it gives me the error "Type Mismatch". For simplicity, I've been storing it as a bitmap, but I also tried .gif and .png in my first attempts.
Note: Apparently the ribbon icons are IPictureDisp objects. If I can just figure out how to load an image from a table into one of those object types, I should be able to use it for the ribbon.
Also, there's a lot of good information on Microsoft's website, but I haven't been able to piece it together into a solution yet. Here's a link: http://msdn.microsoft.com/en-us/library/bb187398.aspx
Well after tedious days of trying to find a better solution, I'm forced to pick between what I feel are various mediocre approaches. I really wanted to just load it directly into a variable, but the only method for doing that requires references to a bunch of dlls and has code that is pretty complicated. To avoid any extra dependencies and to keep my code simpler, I decided to go the route of assigning the table containing the attached images to a form, opening that form in hidden mode and then assigning the picture variables from the form.
For some reason the code that I saw elsewhere that loaded the pictures on demand via this method caused my program to crash and so I had to load the pictures into variables when the program opened and then have the menu bar set the icons from those variables when the menu is selected.
My code is as follows:
Dim Icn(15) As IPictureDisp, IcnLbl(15) As String
Function SetMnuIcn()
Dim Img As Recordset, i As Byte
DoCmd.OpenForm "frmImg", acNormal, , , acFormReadOnly, acHidden
Set Img = Forms!frmImg.Recordset
While Not Img.EOF
i = i + 1
Set Icn(i) = Forms!frmImg!Img.PictureDisp
IcnLbl(i) = Img!Lbl
Img.MoveNext
Wend
DoCmd.Close acForm, "frmImg", acSaveNo
End Function
Sub GetMnuIcn(control As IRibbonControl, ByRef Image)
Set Image = Icn(GetAryLoc(IcnLbl, control.ID, 15))
End Sub
Function GetAryLoc(varValues As Variant, varMatch As Variant, NumOfValues As Integer) As Integer
Dim i As Integer
For i = 1 To NumOfValues
If varValues(i) = varMatch Then GetAryLoc = i
Next
End Function
Note: To ensure that the icons have been loaded prior to when they are needed, I specified SetMnuIcn to run on ribbon load:
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="=SetMnuIcn()">

How to see image data using opencv in visual studio?

I wrote an OPENCV project in VS2010 and the results were not the ones as I expected so I ran the debugger to see where is the problem. When I wanted to see the data inside the image loaded I didn't know how to do it so if I want to see the data inside my images what should I do?
It is pretty simple in matlab for seeing different channel of an image i.e.
a=imread('test.jpg');
p1 = a(:,:,1)
p2 = b(:,:,2)
.
.
In opencv I wrote the same thing but I don't know how to see all the element at once just like Matlab.
a= imread("test.jpg")
split(a,planes);
vector<Mat> T1;
T1 = planes[0];
// How can I see the data inside T1 when debugging the code ?
I think this is what you are looking for - it's a great Visual Studio add-on
https://bitbucket.org/sergiu/opencv-visualizers
Just download the installer, make sure VS is closed, run it, re-open VS and voila! Now, when you point to an OpenCV data structure, all kinds of nice info is showed.
Limitations: I saw some problems with multichannel images (it only shows the first channel) and it also has trouble displaying large matrices. If you want to see raw data in a big matrix, you can use the old good VS trick with debug variables: Stop at a breakpoint, go to Watch tab, and write there
((float*)myMat.data) ,10
Where float is the matrix type, myMat is your matrix, and 10 is the number of values you want to print. It will display the first 10 values at the memory location of myMat.data. If you do not correctly choose the data type, you'll see garbage. In my example, myMat is of type cv::Mat.
And never forget the power of visualizers:
imshow("Image", myMat);
If your data fits into an image. You can use the contrib module's colormap to enhance your visualizers.
I can't actually believe that nobody suggested Image Watch yet. It's the most amazing add-in ever. It shows you a view with all your Mat variables (images (gray and color), matrices) while debugging, there's useful stuff like zooming or contrast-stretching and you can even apply more complex functions directly in the plugin in real-time. It makes debugging of any kind of image operations a breeze and it's immensely helpful if you do calculations and linear algebra stuff with your cv::Mat matrices.
I recommend to use a NativeViewer extension. It actually displays the content of an image in a preview window, not only the properly formatted info.
If you don't want to use a plug-in or extension to Visual Studio, you can access the elements one by one in the debugging watch tab by typing this:
T1.data[T1.step.buf[0]*i + T1.step.buf[1]*j];
where i is the row you want to look at and j is the column.
after downloading imagewatch use the command in watch window
(imagesLoc._Myfirst)[0]
index of image in the vector
You can use the immediate window and the extenshion method like this one
/// <summary>
/// Displays image
/// </summary>
public static void Display (this Mat m, Rect rect = default, string windowName = "")
{
if (string.IsNullOrEmpty(windowName))
{
windowName = m.ToString();
}
var img = rect == default ? m : m.Crop(rect);
double coef = Math.Min(1600d / img.Width, 800d / img.Height);
Cv2.ImShow(windowName, img.Resize(new Size(coef * img.Width, (coef * img.Height) > 1 ? coef * img.Height : 1)));
Cv2.WaitKey();
}
Then you stop at a breakpoint and call yourImage.Display() in the immediate window.
If you can use CLion you can utilize the OpenCV Image Viewer plugin, which displays matrices while debugging just on click.
https://plugins.jetbrains.com/plugin/14371-opencv-image-viewer
Disclaimer: I'm an author of this plugin

VB6: How to switch to pixels instead of twips

I am refactoring a VB6 application. The measurements of any of the controls are in twips. Is it possible in VB6 to set a control to use pixels instead of twips? Thanks
I worked extensively with scalemode back in the day and all I can say is don't bother. It wasn't properly universally supported, which meant that you'll end up converting back to twips for some things anyway.
VB6 is twips based, like it or not, so if you try to do things pixel based, you'll be fighting the current the whole way.
Fortunately VB.net finally ended all that, and is completely pixel based, you can still alter you viewport scaling but .net seems to handle that much better than Vb6.
dim iInPixels as integer
dim iInTwips as integer
iInPixels = 200
iInTwips = iInPixels * Screen.TwipsPerPixelX
iInPixels = iInTwips / Screen.TwipsPerPixelX
As #drventure said, you'll be rowing against the current the whole way, but it really isn't all that bad, as long as you can isolate the logic to a single spot.
Does the ScaleMode Property help?
Returns or sets a value indicating the unit of measurement for coordinates of an object when using graphics methods or when positioning controls.
Microsoft Knowledge Base article: How to Convert Twips to Pixels
The link above is for Access VBA but will work with VB6 as well. I'm not aware of native VB6 functionality to do what you need. From what I remember ScaleMode will not work for what you want to do (despite the fact that it seems to exist to solve your exact problem).
EDIT: As I'm thinking about it, ScaleMode did not solve my problem that I had at the time. Depending on what you are trying to do, it may solve your problem just fine. I'd certainly try that first since it will produce simpler, more maintainable code.
I did it this way.
I got the Twips from Form1.Picture.Width and by dividing with pixelize you get pixels ANYWHERE in VB6 Script.
In General Declarations
Const pixelize As Double = 26.45833333
Command3.Caption = "Pixels: " & Int(Form1.Picture.Width / pixelize) & "x" & Int(Form1.Picture.Height / pixelize)
Works for me, maybe you are helped.

Resources