Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8057709
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T09:07:05+00:00 2026-06-05T09:07:05+00:00

I’m trying to refactor this unsafe code to copy a single ARGB channel from

  • 0

I’m trying to refactor this unsafe code to copy a single ARGB channel from one image to another using System.Runtime.InteropServices.Marshal.Copy as per this example on MSDN but I’m totally lost.

Could anyone walk me through how I would go about it?

public enum ChannelARGB
{
    Blue = 0,
    Green = 1,
    Red = 2,
    Alpha = 3
}

public static void transferOneARGBChannelFromOneBitmapToAnother(
    Bitmap source,
    Bitmap dest,
    ChannelARGB sourceChannel,
    ChannelARGB destChannel )
{
    if ( source.Size!=dest.Size )
        throw new ArgumentException();
    Rectangle r = new Rectangle( Point.Empty, source.Size );
    BitmapData bdSrc = source.LockBits( r, 
                                        ImageLockMode.ReadOnly, 
                                        PixelFormat.Format32bppArgb );
    BitmapData bdDst = dest.LockBits( r, 
                                      ImageLockMode.ReadWrite,
                                      PixelFormat.Format32bppArgb );
    unsafe
    {
        byte* bpSrc = (byte*)bdSrc.Scan0.ToPointer();
        byte* bpDst = (byte*)bdDst.Scan0.ToPointer();
        bpSrc += (int)sourceChannel;
        bpDst += (int)destChannel;
        for ( int i = r.Height * r.Width; i > 0; i-- )
        {
            *bpDst = *bpSrc;
            bpSrc += 4;
            bpDst += 4;
        }
    }
    source.UnlockBits( bdSrc );
    dest.UnlockBits( bdDst );
}

Edit

In an attempt to work through @Ben Voigt walk though I have come up with this so far. Unfortunately I am now getting the following error:

Attempted to read or write protected memory. This is often an
indication that other memory is corrupt.

    private static void TransferOneArgbChannelFromOneBitmapToAnother(
                                         Bitmap source,
                                         Bitmap destination, 
                                         ChannelARGB sourceChannel, 
                                         ChannelARGB destinationChannel)
    {
        if (source.Size != destination.Size)
        {
            throw new ArgumentException();
        }

        Rectangle rectangle = new Rectangle(Point.Empty, source.Size);

        // Lockbits the source.
        BitmapData bitmapDataSource = source.LockBits(rectangle,
                                                  ImageLockMode.ReadWrite,
                                                  PixelFormat.Format32bppArgb);

        // Declare an array to hold the bytes of the bitmap.
        int bytes = bitmapDataSource.Stride * bitmapDataSource.Height;

        // Allocate a buffer for the source image
        byte[] sourceRgbValues = new byte[bytes];

        // Get the address of the first line.
        IntPtr ptrSource = bitmapDataSource.Scan0;

        // Copy the RGB values into the array.
        System.Runtime.InteropServices.Marshal.Copy(ptrSource, 
                                                    sourceRgbValues, 
                                                    0, 
                                                    bytes);

        // Unlockbits the source.
        source.UnlockBits(bitmapDataSource);

        // Lockbits the destination.
        BitmapData bitmapDataDestination = destination.LockBits(rectangle,
                                                  ImageLockMode.ReadWrite,
                                                  PixelFormat.Format32bppArgb);

        // Allocate a buffer for image
        byte[] destinationRgbValues = new byte[bytes];

        IntPtr ptrDestination = bitmapDataDestination.Scan0;

        // Copy the RGB values into the array.
        System.Runtime.InteropServices.Marshal.Copy(ptrDestination,
                                                    destinationRgbValues, 
                                                    0, 
                                                    bytes);

        ptrSource += (int)sourceChannel;
        ptrDestination += (int)destinationChannel;

        for (int i = rectangle.Height * rectangle.Width; i > 0; i--)
        {
            destinationRgbValues[i] = sourceRgbValues[i];
            ptrSource += 4;
            ptrDestination += 4;
        }

        // Copy the RGB values back to the bitmap
        // ******This is where I am getting the exception*******.
        System.Runtime.InteropServices.Marshal.Copy(destinationRgbValues, 
                                                    0, 
                                                    ptrDestination, 
                                                    bytes);

        // Unlock bits the destination.
        destination.UnlockBits(bitmapDataDestination);
    }

Can anyone see what I have done wrong? This is all a bit over my head to be honest. I think I should buy some books.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T09:07:07+00:00Added an answer on June 5, 2026 at 9:07 am
    1. LockBits the source.
    2. Marshal.Copy the source BitmapData to a byte[] buffer.
    3. UnlockBits the source.
    4. LockBits the destination.
    5. Marshal.Copy the destination BitmapData to a byte[] buffer.
    6. Loop through and copy that channel from the source byte[] to the destination byte[] (note, use arithmetic on indexes instead of on pointers)
    7. Marshal.Copy the destination byte[] back to the BitmapData.
    8. UnlockBits the destination.

    I’m not sure what the point is, though. Code that uses Marshal.Copy is just as dangerous as code that uses the unsafe keyword, and should require similar code security permission.

    A potentially more efficient way would be to use ImageAttributes.SetColorMatrix to remove the desired channel from the destination image, remove all other channels from the source image, and then blend. See the example for ColorMatrix

    Or use DirectX (or OpenGL) and a shader that just transfers the one channel.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
Does anyone know how can I replace this 2 symbol below from the string
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
I'm trying to create an if statement in PHP that prevents a single post

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.