Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Create program or function that takes file name as an argument or reads it from standard input, and completes the following task:

  1. Read image from a png file (name given as argument).
  2. Reverse colors in that image, so that for example dark green (0, 75, 30) would become (255, 180, 225) (because 255-0=255, 255-75=180 and 255-30=225). You should not change alpha channel value.
  3. Output that image to a file called a.png (in png format), or show it in GUI window.

This is . Standard loopholes apply.

share|improve this question
    
Is it required to support any optional png features? Are built-in png loading/writing functions acceptable? – Sparr Mar 28 at 22:42
    
@Sparr Optional feature support is optional. Built-in functions are not explicitly disallowed, so I'll assume they are allowed. – Hannes Karppila Mar 28 at 22:44
3  
PNG files can be indexed (each pixel contains a pointer to a color in the colormap) or truecolor (each pixel contains the actual color). Which one do we need to support? Can we choose? In fact, there are five different subformats regarding color. So... ? – Luis Mendo Mar 28 at 23:20
    
@DonMuesli I think any method that provides correct result will be fine. You can assume that the color isn't greyscale, and supporting alpha-channel is optional. I think that using any other mode is acceptable, as long as the task will still be reversing the colors, and colors have (r,g,b)-values. – Hannes Karppila Mar 29 at 9:10

11 Answers 11

ImageMagick display, 7 18 24 bytes

-negate

or

-fx 1-u

The ImageMagick tool display can apply the above "programs" to a png given as the parameter and display the results on screen.

Check out my post on meta about ImageMagick as a programming language. I wrote a prime tester over there as a proof of concept. I am not yet clear on whether or not it is legitimate to omit the "-fx " and get this score down to 3 bytes

share|improve this answer
    
Is this not a standard loophole? It's gotten plenty of upvotes, but it seems like it should be. I guess if Mathematica can have a bunch of these functions built-in, then using any pre-released application (before the asking of the question) to do it for you is fair game, so long as it accepts command-line arguments? – Nate Diamond Mar 29 at 16:01
1  
@NateDiamond Give me about 5 minutes to finish my meta post about "is imagemagick a programming language" and I'll cut this down to 7 bytes and address your question at the same time :) – Sparr Mar 29 at 16:03
6  
@NateDiamond meta.codegolf.stackexchange.com/questions/8828/… – Sparr Mar 29 at 16:18

Pyth, 16 15 13 bytes

.w-LLL255'z\a

Outputs to a.png.

          z    read input
         '     read as RGB triples from file
   LLL         map over rows, then triples, then individual values...
  -   255      ...subtract from 255
.w         \a  write as image to a.png

Thanks to Jakube for 2 bytes!

share|improve this answer
3  
man, i've gotta learn pyth – undergroundmonorail Mar 28 at 22:53
1  
Does Pyth not have bitwise negation (~ or similar)? – Peter Taylor Mar 29 at 7:33
    
@PeterTaylor I don't think it does, surprisingly. (In any case, it would have to be restricted to 8 bits.) – Doorknob Mar 29 at 10:55
    
is there no way to deeply-map with a pfn? – ven Mar 29 at 11:09
1  
@ven @Doorknob Actually you can do it: .w-LLL255'z\a. But don't ask me how this works or why you need LLL and not something like LMM. – Jakube Mar 29 at 12:32

Java, 295

import javax.imageio.*;class V{public static void main(String[]a)throws
Exception{java.awt.image.BufferedImage m=ImageIO.read(new
java.io.File(a[0]));for(int
x=m.getWidth(),y;x-->0;)for(y=m.getHeight();y-->0;)m.setRGB(x,y,m.getRGB(x,y)^-1>>>8);ImageIO.write(m,"png",new
java.io.File("a.png"));}}
share|improve this answer
1  
I like how x-- and x>0 together make a litte arrow showing that x goes up to 0. Why have I never seen/used that before? – LuWi Mar 29 at 14:41
    
Import java.io.File? – nickb Mar 29 at 14:56
1  
@LuWi hehe, I've seen and used it before, some people call it the "goes to" operator, and it's pretty golfy :) – aditsu Mar 29 at 15:40
    
@nickb even if you use the shorter import java.io.*;, it doesn't save any bytes but actually increases the size. – aditsu Mar 29 at 15:42
1  
+1. Cause, y'know. Java. – cat Mar 29 at 19:05

MATL, 10 bytes

255iYi-IYG

There are five different subformats of PNG, depending on how color is encoded. None of them seems to be more "optional" than the others. I chose the most flexible one, Truecolor, in which each pixel can have an arbitrary color. The above code also supports Truecolor with alpha, ignoring the alpha channel.

To know the color subformat of a PNG file: look for the byte sequence [73 72 68 82] near the beginning of the file; and the tenth byte from there will have one of the five values in the table linked above.

How the works

Pretty straightforward:

255    % push 255 to the stack
i      % input filename with extension '.png'
Yi     % read contents of that file as (truecolor) image
-      % subtract
IYG    % show image

Example

I couldn't resist seeing myself inverted, so I downloaded this image (which is in subformat Truecolor with alpha), ran the code (second line is user input)

>> matl 255iYi-IYG
> 'C:\Users\Luis\Desktop\me.png'

and got

enter image description here

share|improve this answer
1  
Your avatar is actually you? I thought it was just your helmet! :P – Upgoat Mar 29 at 22:15

cmd + IrfanView, 19 characters

i_view32 %1 /invert

Just the expensive alternative of Sparr's answer.

share|improve this answer

Tcl, 176 bytes

foreach r [[image c photo -file {*}$argv] d] {set x {}
foreach c $r {lappend x [format #%06X [expr "0xFFFFFF-0x[string ra $c 1 end]"]]}
lappend y $x}
image1 p $y
image1 w a.png

Loads the PNG via the photo image type, gets the image data, converting each row and color by subtracting from #FFFFFF, then writes the file back to disk (as "a.png").

For best results, use TrueColor PNGs, since Tk will try to use the same color resolution as the source image data.

To see the image without sampling problems, add

pack [label .i -image image1]

to the end. (Obviously, this is longer than the disk-save option.)

share|improve this answer

Mathematica, 140 bytes

Export["a.png",SetAlphaChannel[ColorCombine[Most@#],Last@#]&@MapAt[Image[1-ImageData@#]&,ColorSeparate[Import[#],{"R","G","B","A"}],{;;3}]]&
share|improve this answer

Julia, 94 79 bytes

using FileIO
save(ARGS[1],map(x->typeof(x)(1-x.r,1-x.g,1-x.b,1),load(ARGS[1])))

This is a full program that takes a file name as a command line argument and overwrites the given file with the inverted image. It requires that the FileIO and Image package be installed. The latter doesn't need to be imported though.

Call the program from the command line like julia filename.jl /path/to/image.png.

Ungolfed:

using FileIO # required for reading and writing image files

# Load the given image into a matrix where each element is an RGBA value
a = load(ARGS[1])

# Construct a new image matrix as the inverse of `a` by, for each element
# `x` in `a`, constructing a new RGBA value as 1 - the RGB portions of
# `x`, but with an alpha of 1 to avoid transparency.
b = map(x -> typeof(x)(1 - x.r, 1 - x.g, 1 - x.b, 1), a)

# Save the image using the same filename
save(ARGS[1], b)

Example:

regular inverted

share|improve this answer
    
The magpie (?) looks seriously depressed on the second image. – Bálint May 3 at 7:33

R, 124 bytes

p=png::readPNG(readline());p[,,-4]=1-p[,,-4];png("a.png",h=nrow(p),w=ncol(p));par(mar=rep(0,4));plot(as.raster(p));dev.off()

Reads in file name through stdin (readline()).

p=png::readPNG(readline()) #Reads in png as an RGBA array on range [0,1]
p[,,-4]=1-p[,,-4] #Takes the opposite value except on alpha layer
png("a.png",h=nrow(p),w=ncol(p)) #Prepares output png of same size as input
par(mar=rep(0,4)) #Makes the png take the full space of the figure region
plot(as.raster(p)) #Transforms p as a raster so that it can be plotted as is.
dev.off() #Closes the plotting device.

Example Input/Output using the first png I found on this computer :)

Input Output

share|improve this answer

FFmpeg, 10 bytes

Edit: Taking a cue from @Sparr's answer

-vf negate

(the above when passed to ffplay alongwith the image name, will display the negated image)


ffplay %1 -vf negate

The above is saved as a batch file.

share|improve this answer
    
Is FFmpeg a programming language by our standards? I don't know enough about it to be sure. Perhaps ask on meta? – Mego May 3 at 7:55

Python + PIL, 85 bytes

from PIL import Image
lambda a:Image.eval(Image.open(a),lambda x:255-x).save('a.png')

This defines an anonymous function that takes a filename as a string and saves the resultant image to a.png.

Test run:

llama llama out

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.