Pixel Drawing after Loading an Image

So recently I managed to draw pixels to a texture after creating the texture myself - something I wrote about here (http://www.programmersranch.com/2014/02/sdl2-pixel-drawing.html) at my blog. However, what I would really like is to load an image via SDL_LoadBitmap() or IMG_Load() and then manipulate the image’s pixels in the window.

I tried using SDL_LockTexture() hoping that that would give me the texture’s pixels, but I get this error: “SDL_LockTexture(): texture must be streaming”. I can’t make a streaming texture since I’m loading it via IMG_Load(). So what is the right way to draw pixels on a texture you loaded from an image? My current code is below.

Code:

#include <SDL.h>
#include <SDL_image.h>

int main(int argc, char ** argv)
{
bool quit = false;
SDL_Event event;

SDL_Init(SDL_INIT_VIDEO);
IMG_Init(IMG_INIT_JPG);

SDL_Window * window = SDL_CreateWindow("SDL2 Displaying Image",
	SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
SDL_Surface * image = IMG_Load("PICT3159.JPG");
SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer,
	image);

const int pixelCount = image->w * image->h;
Uint32 * pixels;
int pitch = 0;
if (SDL_LockTexture(texture, NULL, (void **)&pixels, &pitch) != 0)
	SDL_ShowSimpleMessageBox(0, "Failed", SDL_GetError(), window);
else
	SDL_UnlockTexture(texture);

while (!quit)
{
	SDL_WaitEvent(&event);

	switch (event.type)
	{
	case SDL_QUIT:
		quit = true;
		break;
	}

	SDL_RenderCopy(renderer, texture, NULL, NULL);
	SDL_RenderPresent(renderer);
}

SDL_DestroyTexture(texture);
SDL_FreeSurface(image);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();

return 0;

}------------------------
Daniel D’Agostino
http://www.programmersranch.com/

OK, I managed to figure this out. You can’t touch the texture pixels directly, so:

  1. Create a static / streaming texture (SDL_CreateTexture()).
  2. Use SDL_ConvertSurfaceFormat() to obtain a new surface with a familiar format (e.g. SDL_PIXELFORMAT_ARGB8888) since images can have differing formats and that can get confusing to deal with when updating pixels.
  3. Use SDL_UpdateTexture() to copy the surface pixels to the texture as you update it.------------------------
    Daniel D’Agostino
    http://www.programmersranch.com/