Good Search Capabilities Often Trump Good Logic

Good Search Capabilities Often Trump Good Logic

Recently, I learned a valuable lesson in modern programming efficiency: Problem-solving abilities often take a backseat to information retrieval and analysis. I was working on an application that saved images extracted from Word 2007’s OOXML file format, and received an application error:

System.Runtime.InteropServices.ExternalException was unhandled

Message=”A generic error occurred in GDI+.”

Source=”System.Drawing”

ErrorCode=-2147467259

 

In OOXML, various “parts” of the document are stored in DocumentPart containers. The various parts have relationships, each with its own ID. The project code had obtained the appropriate DocumentPart containing the image from the document, using the relationship ID associated with that image. It then retrieved the image from the DocumentPart, using the Image.FromStream method, and stored the resulting Image for later use. The code that caused the error was a simple Image.Save command that attempted to save the image in a specified folder.

The error message was no help: What does “A generic error occurred in GDI+” mean, anyhow? Time to review the stack trace:

 

StackTrace:

   at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, 

      EncoderParameters encoderParams)

   at System.Drawing.Image.Save(String filename, ImageFormat format)

   at System.Drawing.Image.Save(String filename)

   at TestOpenXMLSDK2.Form1.btnSaveImages_Click(

      Object sender, EventArgs e)

   at System.Windows.Forms.Control.OnClick(EventArgs e)

   at System.Windows.Forms.Button.OnClick(EventArgs e)

 

Nothing jumps out from that. I had a valid image; the filename was valid; the destination folder existed and contained no existing image with the same filename; the folder wasn’t read-only; I had full permissions on the folder; and there was plenty of room on the disk. Even worse, the code had been running for several days with no problems.

In earlier years, I would have been stuck, but modern programming is fundamentally different. Rather than laboriously solving problems, often by trial-and-error, you can usually solve problems by a simple search. The key to solving this one was the line ErrorCode=-2147467259. Pasting that into Google turned up a discussion that referenced this Microsoft Support page. The information there says basically that if you create a Bitmap from a stream (which I had), that stream must remain open for the lifetime of the Bitmap, because:

“GDI+, and therefore the System.Drawing namespace, may defer the decoding of raw image bits until the bits are required by the image. Additionally, even after the image has been decoded, GDI+ may determine that it is more efficient to discard the memory for a large Bitmap and to re-decode later. Therefore, GDI+ must have access to the source bits for the image for the life of the Bitmap or the Image object.”

I didn’t want to recode the project to keep the stream open, but the page also provided a workaround: You can make a copy of the original bitmap, which removes the requirement to access the source. It provided these instructions:

1.     Construct the original Bitmap from the stream, from the memory, or from the file.

2.     Create a new Bitmap of the same size, with a pixel format of more than 8 bits-per-pixel (BPP).

3.     Use the Graphics.FromImage() method to obtain a Graphics object for the second Bitmap.

4.     Use Graphics.DrawImage() to draw the first Bitmap onto the second Bitmap.

5.     Use Graphics.Dispose() to dispose of the Graphics.

6.     Use Bitmap.Dispose() to dispose of the first Bitmap.

 

It took only a few minutes to add that code, and the project was back on track. But the real point is that the resources available on the web to modern programmers often makes programming much more of an exercise in good search techniques than an exercise in good logic and debugging techniques.

Of course, all this could have been avoided if the Image class had a way to ensure that the source bits would be available even if the originating stream were closed. And it would have been far less irritating if the error message had said “Unable to save because the source stream or file for this image is no longer available.” But that’s another topic.

devx-admin

devx-admin

Share the Post:
Romanian Energy Security

Eastern Europe is Achieving Energy Security

Canada and Romania have solidified their commitment to energy security and independence from Russian energy exports by signing a $3-billion export development agreement. The deal

Seamless Integration

Unlocking Seamless Smart Home Integration

The vision of an intelligently organized and interconnected smart home that conserves time, energy, and resources has long been desired by many homeowners. However, this

New Algorithm

MicroAlgo’s Groundbreaking Algorithm

MicroAlgo Inc. has revealed the creation of a knowledge-augmented backtracking search algorithm, developed through extensive research in evolutionary computational techniques. The algorithm is designed to

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Romanian Energy Security

Eastern Europe is Achieving Energy Security

Canada and Romania have solidified their commitment to energy security and independence from Russian energy exports by signing a $3-billion export development agreement. The deal is centered on constructing two

Seamless Integration

Unlocking Seamless Smart Home Integration

The vision of an intelligently organized and interconnected smart home that conserves time, energy, and resources has long been desired by many homeowners. However, this aspiration has often been hindered

New Algorithm

MicroAlgo’s Groundbreaking Algorithm

MicroAlgo Inc. has revealed the creation of a knowledge-augmented backtracking search algorithm, developed through extensive research in evolutionary computational techniques. The algorithm is designed to boost problem-solving effectiveness, precision, and

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of