... this bit to just be if (replaceOpacity != null) opacity *= replaceOpacity

Actually that's not "replacing" the opacity at all. You sure this works? Won't it have no effect is replaceColor is 255 and reduce opacity if lower?