图片相关

package com.opslab.util.image.GIF;

import java.io.IOException;
import java.io.OutputStream;
/**
* @author: wuhongjun
* @version:1.0
*/
public class Encoder {
private static final int EOF = -1;

private int imgW, imgH;
private byte[] pixAry;
private int initCodeSize;
private int remaining;
private int curPixel;

// GIFCOMPR.C - GIF Image compression routines
//
// Lempel-Ziv compression based on 'compress'. GIF modifications by
// David Rowley (mgardi@watdcsu.waterloo.edu)

// General DEFINEs

static final int BITS = 12;

static final int HSIZE = 5003; // 80% occupancy

// GIF Image compression - modified 'compress'
//
// Based on: compress.c - File compression ala IEEE Computer, June 1984.
//
// By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
// Jim McKie (decvax!mcvax!jim)
// Steve Davies (decvax!vax135!petsd!peora!srd)
// Ken Turkowski (decvax!decwrl!turtlevax!ken)
// James A. Woods (decvax!ihnp4!ames!jaw)
// Joe Orost (decvax!vax135!petsd!joe)

int n_bits; // number of bits/code
int maxbits = BITS; // user settable max # bits/code
int maxcode; // maximum code, given n_bits
int maxmaxcode = 1 << BITS; // should NEVER generate this code

int[] htab = new int[HSIZE];
int[] codetab = new int[HSIZE];

int hsize = HSIZE; // for dynamic table sizing

int free_ent = 0; // first unused entry

// block compression parameters -- after all codes are used up,
// and compression rate changes, start over.
boolean clear_flg = false;

// Algorithm: use open addressing double hashing (no chaining) on the
// prefix code / next character combination. We do a variant of Knuth's
// algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
// secondary probe. Here, the modular division first probe is gives way
// to a faster exclusive-or manipulation. Also do block compression with
// an adaptive reset, whereby the code table is cleared when the compression
// ratio decreases, but after the table fills. The variable-length output
// codes are re-sized at this point, and a special CLEAR code is generated
// for the decompressor. Late addition: construct the table according to
// file size for noticeable speed improvement on small files. Please direct
// questions about this implementation to ames!jaw.

int g_init_bits;

int ClearCode;
int EOFCode;

// output
//
// Output the given code.
// Inputs:
// code: A n_bits-bit integer. If == -1, then EOF. This assumes
// that n_bits =< wordsize - 1.
// Outputs:
// Outputs code to the file.
// Assumptions:
// Chars are 8 bits long.
// Algorithm:
// Maintain a BITS character long buffer (so that 8 codes will
// fit in it exactly). Use the VAX insv instruction to insert each
// code in turn. When the buffer fills up empty it and start over.

int cur_accum = 0;
int cur_bits = 0;

int masks[] =
{
0x0000,
0x0001,
0x0003,
0x0007,
0x000F,
0x001F,
0x003F,
0x007F,
0x00FF,
0x01FF,
0x03FF,
0x07FF,
0x0FFF,
0x1FFF,
0x3FFF,
0x7FFF,
0xFFFF };

// Number of characters so far in this 'packet'
int a_count;

// Define the storage for the packet accumulator
byte[] accum = new byte[256];

//----------------------------------------------------------------------------
Encoder(int width, int height, byte[] pixels, int color_depth) {
imgW = width;
imgH = height;
pixAry = pixels;
initCodeSize = Math.max(2, color_depth);
}

// Add a character to the end of the current packet, and if it is 254
// characters, flush the packet to disk.
void char_out(byte c, OutputStream outs) throws IOException {
accum[a_count++] = c;
if (a_count >= 254)
flush_char(outs);
}

// Clear out the hash table

// table clear for block compress
void cl_block(OutputStream outs) throws IOException {
cl_hash(hsize);
free_ent = ClearCode + 2;
clear_flg = true;

output(ClearCode, outs);
}

// reset code table
void cl_hash(int hsize) {
for (int i = 0; i < hsize; ++i)
htab[i] = -1;
}

void compress(int init_bits, OutputStream outs) throws IOException {
int fcode;
int i /* = 0 */;
int c;
int ent;
int disp;
int hsize_reg;
int hshift;

// Set up the globals: g_init_bits - initial number of bits
g_init_bits = init_bits;

// Set up the necessary values
clear_flg = false;
n_bits = g_init_bits;
maxcode = MAXCODE(n_bits);

ClearCode = 1 << (init_bits - 1);
EOFCode = ClearCode + 1;
free_ent = ClearCode + 2;

a_count = 0; // clear packet

ent = nextPixel();

hshift = 0;
for (fcode = hsize; fcode < 65536; fcode *= 2)
++hshift;
hshift = 8 - hshift; // set hash code range bound

hsize_reg = hsize;
cl_hash(hsize_reg); // clear hash table

output(ClearCode, outs);

outer_loop : while ((c = nextPixel()) != EOF) {
fcode = (c << maxbits) + ent;
i = (c << hshift) ^ ent; // xor hashing

if (htab[i] == fcode) {
ent = codetab[i];
continue;
} else if (htab[i] >= 0) // non-empty slot
{
disp = hsize_reg - i; // secondary hash (after G. Knott)
if (i == 0)
disp = 1;
do {
if ((i -= disp) < 0)
i += hsize_reg;

if (htab[i] == fcode) {
ent = codetab[i];
continue outer_loop;
}
} while (htab[i] >= 0);
}
output(ent, outs);
ent = c;
if (free_ent < maxmaxcode) {
codetab[i] = free_ent++; // code -> hashtable
htab[i] = fcode;
} else
cl_block(outs);
}
// Put out the final code.
output(ent, outs);
output(EOFCode, outs);
}

//----------------------------------------------------------------------------
void encode(OutputStream os) throws IOException {
os.write(initCodeSize); // write "initial code size" byte

remaining = imgW * imgH; // reset navigation variables
curPixel = 0;

compress(initCodeSize + 1, os); // compress and write the pixel data

os.write(0); // write block terminator
}

// Flush the packet to disk, and reset the accumulator
void flush_char(OutputStream outs) throws IOException {
if (a_count > 0) {
outs.write(a_count);
outs.write(accum, 0, a_count);
a_count = 0;
}
}

final int MAXCODE(int n_bits) {
return (1 << n_bits) - 1;
}

//----------------------------------------------------------------------------
// Return the next pixel from the image
//----------------------------------------------------------------------------
private int nextPixel() {
if (remaining == 0)
return EOF;

--remaining;

byte pix = pixAry[curPixel++];

return pix & 0xff;
}

void output(int code, OutputStream outs) throws IOException {
cur_accum &= masks[cur_bits];

if (cur_bits > 0)
cur_accum |= (code << cur_bits);
else
cur_accum = code;

cur_bits += n_bits;

while (cur_bits >= 8) {
char_out((byte) (cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}

// If the next entry is going to be too big for the code size,
// then increase it, if possible.
if (free_ent > maxcode || clear_flg) {
if (clear_flg) {
maxcode = MAXCODE(n_bits = g_init_bits);
clear_flg = false;
} else {
++n_bits;
if (n_bits == maxbits)
maxcode = maxmaxcode;
else
maxcode = MAXCODE(n_bits);
}
}

if (code == EOFCode) {
// At EOF, write the rest of the buffer.
while (cur_bits > 0) {
char_out((byte) (cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}

flush_char(outs);
}
}
}

 

 

package com.opslab.util.image.GIF;


import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* Class AnimatedGifEncoder - Encodes a GIF file consisting of one or
* more frames.
* <pre>
* Example:
* AnimatedGifEncoder e = new AnimatedGifEncoder();
* e.start(outputFileName);
* e.setDelay(1000); // 1 frame per sec
* e.addFrame(image1);
* e.addFrame(image2);
* e.finish();
* </pre>
* No copyright asserted on the source code of this class. May be used
* for any purpose, however, refer to the Unisys LZW patent for restrictions
* on use of the associated Encoder class. Please forward any corrections
* to questions at fmsware.com.
*
* @author wuhongjun
* @version 1.03 November 2003
*
*/
public class GifEncoder {
protected int width; // image size
protected int height;
protected Color transparent = null; // transparent color if given
protected int transIndex; // transparent index in color table
protected int repeat = -1; // no repeat
protected int delay = 0; // frame delay (hundredths)
protected boolean started = false; // ready to output frames
protected OutputStream out;
protected BufferedImage image; // current frame
protected byte[] pixels; // BGR byte array from frame
protected byte[] indexedPixels; // converted frame indexed to palette
protected int colorDepth; // number of bit planes
protected byte[] colorTab; // RGB palette
protected boolean[] usedEntry = new boolean[256]; // active palette entries
protected int palSize = 7; // color table size (bits-1)
protected int dispose = -1; // disposal code (-1 = use default)
protected boolean closeStream = false; // close stream when finished
protected boolean firstFrame = true;
protected boolean sizeSet = false; // if false, get size from first frame
protected int sample = 10; // default sample interval for quantizer

/**
* Sets the delay time between each frame, or changes it
* for subsequent frames (applies to last frame added).
*
* @param ms int delay time in milliseconds
*/
public void setDelay(int ms) {
delay = Math.round(ms / 10.0f);
}

/**
* Sets the GIF frame disposal code for the last added frame
* and any subsequent frames. Default is 0 if no transparent
* color has been set, otherwise 2.
* @param code int disposal code.
*/
public void setDispose(int code) {
if (code >= 0) {
dispose = code;
}
}

/**
* Sets the number of times the set of GIF frames
* should be played. Default is 1; 0 means play
* indefinitely. Must be invoked before the first
* image is added.
*
* @param iter int number of iterations.
* @return
*/
public void setRepeat(int iter) {
if (iter >= 0) {
repeat = iter;
}
}

/**
* Sets the transparent color for the last added frame
* and any subsequent frames.
* Since all colors are subject to modification
* in the quantization process, the color in the final
* palette for each frame closest to the given color
* becomes the transparent color for that frame.
* May be set to null to indicate no transparent color.
*
* @param c Color to be treated as transparent on display.
*/
public void setTransparent(Color c) {
transparent = c;
}

/**
* Adds next GIF frame. The frame is not written immediately, but is
* actually deferred until the next frame is received so that timing
* data can be inserted. Invoking <code>finish()</code> flushes all
* frames. If <code>setSize</code> was not invoked, the size of the
* first image is used for all subsequent frames.
*
* @param im BufferedImage containing frame to write.
* @return true if successful.
*/
public boolean addFrame(BufferedImage im) {
if ((im == null) || !started) {
return false;
}
boolean ok = true;
try {
if (!sizeSet) {
// use first frame's size
setSize(im.getWidth(), im.getHeight());
}
image = im;
getImagePixels(); // convert to correct format if necessary
analyzePixels(); // build color table & map pixels
if (firstFrame) {
writeLSD(); // logical screen descriptior
writePalette(); // global color table
if (repeat >= 0) {
// use NS app extension to indicate reps
writeNetscapeExt();
}
}
writeGraphicCtrlExt(); // write graphic control extension
writeImageDesc(); // image descriptor
if (!firstFrame) {
writePalette(); // local color table
}
writePixels(); // encode and write pixel data
firstFrame = false;
} catch (IOException e) {
ok = false;
}

return ok;
}

//added by alvaro
public boolean outFlush() {
boolean ok = true;
try {
out.flush();
return ok;
} catch (IOException e) {
ok = false;
}

return ok;
}

public byte[] getFrameByteArray() {
return ((ByteArrayOutputStream) out).toByteArray();
}

/**
* Flushes any pending data and closes output file.
* If writing to an OutputStream, the stream is not
* closed.
*/
public boolean finish() {
if (!started) return false;
boolean ok = true;
started = false;
try {
out.write(0x3b); // gif trailer
out.flush();
if (closeStream) {
out.close();
}
} catch (IOException e) {
ok = false;
}

return ok;
}

public void reset() {
// reset for subsequent use
transIndex = 0;
out = null;
image = null;
pixels = null;
indexedPixels = null;
colorTab = null;
closeStream = false;
firstFrame = true;
}

/**
* Sets frame rate in frames per second. Equivalent to
* <code>setDelay(1000/fps)</code>.
*
* @param fps float frame rate (frames per second)
*/
public void setFrameRate(float fps) {
if (fps != 0f) {
delay = Math.round(100f / fps);
}
}

/**
* Sets quality of color quantization (conversion of images
* to the maximum 256 colors allowed by the GIF specification).
* Lower values (minimum = 1) produce better colors, but slow
* processing significantly. 10 is the default, and produces
* good color mapping at reasonable speeds. Values greater
* than 20 do not yield significant improvements in speed.
*
* @param quality int greater than 0.
* @return
*/
public void setQuality(int quality) {
if (quality < 1) quality = 1;
sample = quality;
}

/**
* Sets the GIF frame size. The default size is the
* size of the first frame added if this method is
* not invoked.
*
* @param w int frame width.
* @param h int frame width.
*/
public void setSize(int w, int h) {
if (started && !firstFrame) return;
width = w;
height = h;
if (width < 1) width = 320;
if (height < 1) height = 240;
sizeSet = true;
}

/**
* Initiates GIF file creation on the given stream. The stream
* is not closed automatically.
*
* @param os OutputStream on which GIF images are written.
* @return false if initial write failed.
*/
public boolean start(OutputStream os) {
if (os == null) return false;
boolean ok = true;
closeStream = false;
out = os;
try {
writeString("GIF89a"); // header
} catch (IOException e) {
ok = false;
}
return started = ok;
}

/**
* Initiates writing of a GIF file with the specified name.
*
* @param file String containing output file name.
* @return false if open or initial write failed.
*/
public boolean start(String file) {
boolean ok = true;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
ok = start(out);
closeStream = true;
} catch (IOException e) {
ok = false;
}
return started = ok;
}

/**
* Analyzes image colors and creates color map.
*/
protected void analyzePixels() {
int len = pixels.length;
int nPix = len / 3;
indexedPixels = new byte[nPix];
Quant nq = new Quant(pixels, len, sample);
// initialize quantizer
colorTab = nq.process(); // create reduced palette
// convert map from BGR to RGB
for (int i = 0; i < colorTab.length; i += 3) {
byte temp = colorTab[i];
colorTab[i] = colorTab[i + 2];
colorTab[i + 2] = temp;
usedEntry[i / 3] = false;
}
// map image pixels to new palette
int k = 0;
for (int i = 0; i < nPix; i++) {
int index =
nq.map(pixels[k++] & 0xff,
pixels[k++] & 0xff,
pixels[k++] & 0xff);
usedEntry[index] = true;
indexedPixels[i] = (byte) index;
}
pixels = null;
colorDepth = 8;
palSize = 7;
// get closest match to transparent color if specified
if (transparent != null) {
transIndex = findClosest(transparent);
}
}

/**
* Returns index of palette color closest to c
*
*/
protected int findClosest(Color c) {
if (colorTab == null) return -1;
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
int minpos = 0;
int dmin = 256 * 256 * 256;
int len = colorTab.length;
for (int i = 0; i < len;) {
int dr = r - (colorTab[i++] & 0xff);
int dg = g - (colorTab[i++] & 0xff);
int db = b - (colorTab[i] & 0xff);
int d = dr * dr + dg * dg + db * db;
int index = i / 3;
if (usedEntry[index] && (d < dmin)) {
dmin = d;
minpos = index;
}
i++;
}
return minpos;
}

/**
* Extracts image pixels into byte array "pixels"
*/
protected void getImagePixels() {
int w = image.getWidth();
int h = image.getHeight();
int type = image.getType();
if ((w != width)
|| (h != height)
|| (type != BufferedImage.TYPE_3BYTE_BGR)) {
// create new image with right size/format
BufferedImage temp =
new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = temp.createGraphics();
g.drawImage(image, 0, 0, null);
image = temp;
}
pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
}

/**
* Writes Graphic Control Extension
*/
protected void writeGraphicCtrlExt() throws IOException {
out.write(0x21); // extension introducer
out.write(0xf9); // GCE label
out.write(4); // data block size
int transp, disp;
if (transparent == null) {
transp = 0;
disp = 0; // dispose = no action
} else {
transp = 1;
disp = 2; // force clear if using transparent color
}
if (dispose >= 0) {
disp = dispose & 7; // user override
}
disp <<= 2;

// packed fields
out.write(0 | // 1:3 reserved
disp | // 4:6 disposal
0 | // 7 user input - 0 = none
transp); // 8 transparency flag

writeShort(delay); // delay x 1/100 sec
out.write(transIndex); // transparent color index
out.write(0); // block terminator
}

/**
* Writes Image Descriptor
*/
protected void writeImageDesc() throws IOException {
out.write(0x2c); // image separator
writeShort(0); // image position x,y = 0,0
writeShort(0);
writeShort(width); // image size
writeShort(height);
// packed fields
if (firstFrame) {
// no LCT - GCT is used for first (or only) frame
out.write(0);
} else {
// specify normal LCT
out.write(0x80 | // 1 local color table 1=yes
0 | // 2 interlace - 0=no
0 | // 3 sorted - 0=no
0 | // 4-5 reserved
palSize); // 6-8 size of color table
}
}

/**
* Writes Logical Screen Descriptor
*/
protected void writeLSD() throws IOException {
// logical screen size
writeShort(width);
writeShort(height);
// packed fields
out.write((0x80 | // 1 : global color table flag = 1 (gct used)
0x70 | // 2-4 : color resolution = 7
0x00 | // 5 : gct sort flag = 0
palSize)); // 6-8 : gct size

out.write(0); // background color index
out.write(0); // pixel aspect ratio - assume 1:1
}

/**
* Writes Netscape application extension to define
* repeat count.
*/
protected void writeNetscapeExt() throws IOException {
out.write(0x21); // extension introducer
out.write(0xff); // app extension label
out.write(11); // block size
writeString("NETSCAPE" + "2.0"); // app id + auth code
out.write(3); // sub-block size
out.write(1); // loop sub-block id
writeShort(repeat); // loop count (extra iterations, 0=repeat forever)
out.write(0); // block terminator
}

/**
* Writes color table
*/
protected void writePalette() throws IOException {
out.write(colorTab, 0, colorTab.length);
int n = (3 * 256) - colorTab.length;
for (int i = 0; i < n; i++) {
out.write(0);
}
}

/**
* Encodes and writes pixel data
*/
protected void writePixels() throws IOException {
Encoder encoder = new Encoder(width, height, indexedPixels, colorDepth);
encoder.encode(out);
}

/**
* Write 16-bit value to output stream, LSB first
*/
protected void writeShort(int value) throws IOException {
out.write(value & 0xff);
out.write((value >> 8) & 0xff);
}

/**
* Writes string to output stream
*/
protected void writeString(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
out.write((byte) s.charAt(i));
}
}
}

 

 

package com.opslab.util.image.GIF;

/**
* Created by Administrator on 2016/4/23 0023.
*/
public class Quant {
protected static final int netsize = 256; /* number of colours used */

/* four primes near 500 - assume no image has a length so large */
/* that it is divisible by all four primes */
protected static final int prime1 = 499;
protected static final int prime2 = 491;
protected static final int prime3 = 487;
protected static final int prime4 = 503;

protected static final int minpicturebytes = (3 * prime4);
/* minimum size for input image */

/* Program Skeleton
----------------
[select samplefac in range 1..30]
[read image from input file]
pic = (unsigned char*) malloc(3*width*height);
initnet(pic,3*width*height,samplefac);
learn();
unbiasnet();
[write output image header, using writecolourmap(f)]
inxbuild();
write output image using inxsearch(b,g,r) */

/* Network Definitions
------------------- */

protected static final int maxnetpos = (netsize - 1);
protected static final int netbiasshift = 4; /* bias for colour values */
protected static final int ncycles = 100; /* no. of learning cycles */

/* defs for freq and bias */
protected static final int intbiasshift = 16; /* bias for fractions */
protected static final int intbias = (((int) 1) << intbiasshift);
protected static final int gammashift = 10; /* gamma = 1024 */
protected static final int gamma = (((int) 1) << gammashift);
protected static final int betashift = 10;
protected static final int beta = (intbias >> betashift); /* beta = 1/1024 */
protected static final int betagamma =
(intbias << (gammashift - betashift));

/* defs for decreasing radius factor */
protected static final int initrad = (netsize >> 3); /* for 256 cols, radius starts */
protected static final int radiusbiasshift = 6; /* at 32.0 biased by 6 bits */
protected static final int radiusbias = (((int) 1) << radiusbiasshift);
protected static final int initradius = (initrad * radiusbias); /* and decreases by a */
protected static final int radiusdec = 30; /* factor of 1/30 each cycle */

/* defs for decreasing alpha factor */
protected static final int alphabiasshift = 10; /* alpha starts at 1.0 */
protected static final int initalpha = (((int) 1) << alphabiasshift);

protected int alphadec; /* biased by 10 bits */

/* radbias and alpharadbias used for radpower calculation */
protected static final int radbiasshift = 8;
protected static final int radbias = (((int) 1) << radbiasshift);
protected static final int alpharadbshift = (alphabiasshift + radbiasshift);
protected static final int alpharadbias = (((int) 1) << alpharadbshift);

/* Types and Global Variables
-------------------------- */

protected byte[] thepicture; /* the input image itself */
protected int lengthcount; /* lengthcount = H*W*3 */

protected int samplefac; /* sampling factor 1..30 */

// typedef int pixel[4]; /* BGRc */
protected int[][] network; /* the network itself - [netsize][4] */

protected int[] netindex = new int[256];
/* for network lookup - really 256 */

protected int[] bias = new int[netsize];
/* bias and freq arrays for learning */
protected int[] freq = new int[netsize];
protected int[] radpower = new int[initrad];
/* radpower for precomputation */

/* Initialise network in range (0,0,0) to (255,255,255) and set parameters
----------------------------------------------------------------------- */
public Quant(byte[] thepic, int len, int sample) {

int i;
int[] p;

thepicture = thepic;
lengthcount = len;
samplefac = sample;

network = new int[netsize][];
for (i = 0; i < netsize; i++) {
network[i] = new int[4];
p = network[i];
p[0] = p[1] = p[2] = (i << (netbiasshift + 8)) / netsize;
freq[i] = intbias / netsize; /* 1/netsize */
bias[i] = 0;
}
}

public byte[] colorMap() {
byte[] map = new byte[3 * netsize];
int[] index = new int[netsize];
for (int i = 0; i < netsize; i++)
index[network[i][3]] = i;
int k = 0;
for (int i = 0; i < netsize; i++) {
int j = index[i];
map[k++] = (byte) (network[j][0]);
map[k++] = (byte) (network[j][1]);
map[k++] = (byte) (network[j][2]);
}
return map;
}

/* Insertion sort of network and building of netindex[0..255] (to do after unbias)
------------------------------------------------------------------------------- */
public void inxbuild() {

int i, j, smallpos, smallval;
int[] p;
int[] q;
int previouscol, startpos;

previouscol = 0;
startpos = 0;
for (i = 0; i < netsize; i++) {
p = network[i];
smallpos = i;
smallval = p[1]; /* index on g */
/* find smallest in i..netsize-1 */
for (j = i + 1; j < netsize; j++) {
q = network[j];
if (q[1] < smallval) { /* index on g */
smallpos = j;
smallval = q[1]; /* index on g */
}
}
q = network[smallpos];
/* swap p (i) and q (smallpos) entries */
if (i != smallpos) {
j = q[0];
q[0] = p[0];
p[0] = j;
j = q[1];
q[1] = p[1];
p[1] = j;
j = q[2];
q[2] = p[2];
p[2] = j;
j = q[3];
q[3] = p[3];
p[3] = j;
}
/* smallval entry is now in position i */
if (smallval != previouscol) {
netindex[previouscol] = (startpos + i) >> 1;
for (j = previouscol + 1; j < smallval; j++)
netindex[j] = i;
previouscol = smallval;
startpos = i;
}
}
netindex[previouscol] = (startpos + maxnetpos) >> 1;
for (j = previouscol + 1; j < 256; j++)
netindex[j] = maxnetpos; /* really 256 */
}

/* Main Learning Loop
------------------ */
public void learn() {

int i, j, b, g, r;
int radius, rad, alpha, step, delta, samplepixels;
byte[] p;
int pix, lim;

if (lengthcount < minpicturebytes)
samplefac = 1;
alphadec = 30 + ((samplefac - 1) / 3);
p = thepicture;
pix = 0;
lim = lengthcount;
samplepixels = lengthcount / (3 * samplefac);
delta = samplepixels / ncycles;
alpha = initalpha;
radius = initradius;

rad = radius >> radiusbiasshift;
if (rad <= 1)
rad = 0;
for (i = 0; i < rad; i++)
radpower[i] =
alpha * (((rad * rad - i * i) * radbias) / (rad * rad));

//fprintf(stderr,"beginning 1D learning: initial radius=%d\n", rad);

if (lengthcount < minpicturebytes)
step = 3;
else if ((lengthcount % prime1) != 0)
step = 3 * prime1;
else {
if ((lengthcount % prime2) != 0)
step = 3 * prime2;
else {
if ((lengthcount % prime3) != 0)
step = 3 * prime3;
else
step = 3 * prime4;
}
}

i = 0;
while (i < samplepixels) {
b = (p[pix + 0] & 0xff) << netbiasshift;
g = (p[pix + 1] & 0xff) << netbiasshift;
r = (p[pix + 2] & 0xff) << netbiasshift;
j = contest(b, g, r);

altersingle(alpha, j, b, g, r);
if (rad != 0)
alterneigh(rad, j, b, g, r); /* alter neighbours */

pix += step;
if (pix >= lim)
pix -= lengthcount;

i++;
if (delta == 0)
delta = 1;
if (i % delta == 0) {
alpha -= alpha / alphadec;
radius -= radius / radiusdec;
rad = radius >> radiusbiasshift;
if (rad <= 1)
rad = 0;
for (j = 0; j < rad; j++)
radpower[j] =
alpha * (((rad * rad - j * j) * radbias) / (rad * rad));
}
}
//fprintf(stderr,"finished 1D learning: final alpha=%f !\n",((float)alpha)/initalpha);
}

/* Search for BGR values 0..255 (after net is unbiased) and return colour index
---------------------------------------------------------------------------- */
public int map(int b, int g, int r) {

int i, j, dist, a, bestd;
int[] p;
int best;

bestd = 1000; /* biggest possible dist is 256*3 */
best = -1;
i = netindex[g]; /* index on g */
j = i - 1; /* start at netindex[g] and work outwards */

while ((i < netsize) || (j >= 0)) {
if (i < netsize) {
p = network[i];
dist = p[1] - g; /* inx key */
if (dist >= bestd)
i = netsize; /* stop iter */
else {
i++;
if (dist < 0)
dist = -dist;
a = p[0] - b;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
if (j >= 0) {
p = network[j];
dist = g - p[1]; /* inx key - reverse dif */
if (dist >= bestd)
j = -1; /* stop iter */
else {
j--;
if (dist < 0)
dist = -dist;
a = p[0] - b;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
}
return (best);
}
public byte[] process() {
learn();
unbiasnet();
inxbuild();
return colorMap();
}

/* Unbias network to give byte values 0..255 and record position i to prepare for sort
----------------------------------------------------------------------------------- */
public void unbiasnet() {

int i, j;

for (i = 0; i < netsize; i++) {
network[i][0] >>= netbiasshift;
network[i][1] >>= netbiasshift;
network[i][2] >>= netbiasshift;
network[i][3] = i; /* record colour no */
}
}

/* Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in radpower[|i-j|]
--------------------------------------------------------------------------------- */
protected void alterneigh(int rad, int i, int b, int g, int r) {

int j, k, lo, hi, a, m;
int[] p;

lo = i - rad;
if (lo < -1)
lo = -1;
hi = i + rad;
if (hi > netsize)
hi = netsize;

j = i + 1;
k = i - 1;
m = 1;
while ((j < hi) || (k > lo)) {
a = radpower[m++];
if (j < hi) {
p = network[j++];
try {
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
} catch (Exception e) {
} // prevents 1.3 miscompilation
}
if (k > lo) {
p = network[k--];
try {
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
} catch (Exception e) {
}
}
}
}

/* Move neuron i towards biased (b,g,r) by factor alpha
---------------------------------------------------- */
protected void altersingle(int alpha, int i, int b, int g, int r) {

/* alter hit neuron */
int[] n = network[i];
n[0] -= (alpha * (n[0] - b)) / initalpha;
n[1] -= (alpha * (n[1] - g)) / initalpha;
n[2] -= (alpha * (n[2] - r)) / initalpha;
}

/* Search for biased BGR values
---------------------------- */
protected int contest(int b, int g, int r) {

/* finds closest neuron (min dist) and updates freq */
/* finds best neuron (min dist-bias) and returns position */
/* for frequently chosen neurons, freq[i] is high and bias[i] is negative */
/* bias[i] = gamma*((1/netsize)-freq[i]) */

int i, dist, a, biasdist, betafreq;
int bestpos, bestbiaspos, bestd, bestbiasd;
int[] n;

bestd = ~(((int) 1) << 31);
bestbiasd = bestd;
bestpos = -1;
bestbiaspos = bestpos;

for (i = 0; i < netsize; i++) {
n = network[i];
dist = n[0] - b;
if (dist < 0)
dist = -dist;
a = n[1] - g;
if (a < 0)
a = -a;
dist += a;
a = n[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
bestpos = i;
}
biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));
if (biasdist < bestbiasd) {
bestbiasd = biasdist;
bestbiaspos = i;
}
betafreq = (freq[i] >> betashift);
freq[i] -= betafreq;
bias[i] += (betafreq << gammashift);
}
freq[bestpos] += beta;
bias[bestpos] -= betagamma;
return (bestbiaspos);
}
}

 

 

package com.opslab.util.image;

import com.opslab.util.image.GIF.GifEncoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
* 具体用于实现生成验证码图片的方法
*/
public final class CaptchaUtil {
protected static Font font = new Font("Verdana", Font.ITALIC|Font.BOLD, 28); // 字体
/**
* 产生0--num的随机数,不包括num
* @param num 数字
* @return int 随机数字
*/
public static int num(int num)
{
return (new Random()).nextInt(num);
}
/**
* 给定范围获得随机颜色
* @return Color 随机颜色
*/
protected static Color color(int fc, int bc)
{
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + num(bc - fc);
int g = fc + num(bc - fc);
int b = fc + num(bc - fc);
return new Color(r, g, b);
}


public static boolean pngCaptcha(String randomStr,int width,int height,String file){
char[] strs = randomStr.toCharArray();
try(OutputStream out = new FileOutputStream(file))
{
BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D)bi.getGraphics();
AlphaComposite ac3;
Color color ;
int len = strs.length;
g.setColor(Color.WHITE);
g.fillRect(0,0,width,height);
for(int i=0;i<15;i++){
color = color(150, 250);
g.setColor(color);
g.drawOval(num(width), num(height), 5+num(10), 5+num(10));
}
g.setFont(font);
int h = height - ((height - font.getSize()) >>1),
w = width/len,
size = w-font.getSize()+1;
for(int i=0;i<len;i++){
// 指定透明度
ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);
g.setComposite(ac3);
// 对每个字符都用随机颜色
color = new Color(20 + num(110), 30 + num(110), 30 + num(110));
g.setColor(color);
g.drawString(strs[i]+"",(width-(len-i)*w)+size, h-4);
}
ImageIO.write(bi, "png", out);
out.flush();
return true;
}catch (IOException e){
return false;
}
}

public static boolean gifCaptcha(String randomStr,int width,int height,String file){
char[] rands = randomStr.toCharArray();
int len = rands.length;
try(OutputStream out = new FileOutputStream(file))
{
// gif编码类,这个利用了洋人写的编码类,所有类都在附件中
GifEncoder gifEncoder = new GifEncoder();
//生成字符
gifEncoder.start(out);
gifEncoder.setQuality(180);
gifEncoder.setDelay(100);
gifEncoder.setRepeat(0);
BufferedImage frame;
Color fontcolor[]=new Color[len];
for(int i=0;i<len;i++)
{
fontcolor[i]=new Color(20 + num(110), 20 + num(110), 20 + num(110));
}
for(int i=0;i<len;i++)
{
frame=graphicsImage(fontcolor, rands, i,width,height,len);
gifEncoder.addFrame(frame);
frame.flush();
}
gifEncoder.finish();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}

/**
* 画随机码图
* @param fontcolor 随机字体颜色
* @param strs 字符数组
* @param flag 透明度使用
* @return BufferedImage
*/
private static BufferedImage graphicsImage(Color[] fontcolor,char[] strs,int flag,int width,int height,int len){
BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
//或得图形上下文
//Graphics2D g2d=image.createGraphics();
Graphics2D g2d = (Graphics2D)image.getGraphics();
//利用指定颜色填充背景
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height);
AlphaComposite ac3;
int h = height - ((height - font.getSize()) >>1) ;
int w = width/len;
g2d.setFont(font);
for(int i=0;i<len;i++) {
ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getAlpha(flag, i,len));
g2d.setComposite(ac3);
g2d.setColor(fontcolor[i]);
g2d.drawOval(num(width), num(height), 5+num(10), 5+num(10));
g2d.drawString(strs[i]+"", (width-(len-i)*w)+(w-font.getSize())+1, h-4);
}
g2d.dispose();
return image;
}

/**
* 获取透明度,从0到1,自动计算步长
* @return float 透明度
*/
private static float getAlpha(int i,int j,int len) {
int num = i+j;
float r = (float)1/len,s = (len+1) * r;
return num > len ? (num *r - s) : num * r;
}
}

 

package com.opslab.util.image;

import java.awt.Color;
/**
* 颜色相关的工具类
*/
public final class ColorUtil {
/**
* 16进制转Color对象
* color:RGB颜色
* @param str
* @return
*/
public final static Color String2Color(String str) {
int i = Integer.parseInt(str.substring(1), 16);
return new Color(i);
}

/**
* Color对象转16进制
* @param color
* @return
*/
public final static String Color2String(Color color) {
String R = Integer.toHexString(color.getRed());
R = R.length()<2?('0'+R):R;
String B = Integer.toHexString(color.getBlue());
B = B.length()<2?('0'+B):B;
String G = Integer.toHexString(color.getGreen());
G = G.length()<2?('0'+G):G;
return '#'+R+B+G;
}
}

 

package com.opslab.util.image;

import java.util.Random;

/**
* 生成图片验证码
*/
public final class ImageCaptcha {
//指定图片的宽度
private static int width =200;
//指定图片的高度
private static int height= 40;
//指定所以的字符
public static String CHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static String getCHAR() {
return CHAR;
}

public static void setCHAR(String CHAR) {
ImageCaptcha.CHAR = CHAR;
}

public static int getWidth() {
return width;
}

public static void setWidth(int width) {
ImageCaptcha.width = width;
}

public static int getHeight() {
return height;
}

public static void setHeight(int height) {
ImageCaptcha.height = height;
}

/**
* 随机指定长度的字符串
* @param len
* @return
*/
private static String randomStr(int len){
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < len; i++) {
sb.append(CHAR.charAt(random.nextInt(CHAR.length())));
}
return sb.toString();

}

/**
* 生产一张png格式的验证图片在指定的位置
* @param strlen 验证码长度
* @param file 文件位置
* @return 是否成功
*/
public static String pngCaptcha(int strlen,String file){
String random = randomStr(strlen);
if(CaptchaUtil.pngCaptcha(random,width,height,file)){
return random;
}
return "";
}

public static String gifCaptch(int strlen,String file){
String random = randomStr(strlen);
if(CaptchaUtil.gifCaptcha(random,width,height,file)){
return random;
}
return "";
}

public static void main(String[] args) {
gifCaptch(4,"C:\\Users\\Administrator\\Desktop\\新建文件夹 (2)\\111.gif");
}
}

 

package com.opslab.util.image;

import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
* 图片比较
*/
public final class ImageCompare {
private static Logger logger = Logger.getLogger(ImageCompare.class);

/**
* 改变成二进制码
*
* @param file
* @return
*/
public static String[][] getPX(File file) {
int[] rgb = new int[3];

BufferedImage bi = null;
try {
bi = ImageIO.read(file);
} catch (Exception e) {
e.printStackTrace();
}

int width = bi.getWidth();
int height = bi.getHeight();
int minx = bi.getMinX();
int miny = bi.getMinY();
String[][] list = new String[width][height];
for (int i = minx; i < width; i++) {
for (int j = miny; j < height; j++) {
int pixel = bi.getRGB(i, j);
rgb[0] = (pixel & 0xff0000) >> 16;
rgb[1] = (pixel & 0xff00) >> 8;
rgb[2] = (pixel & 0xff);
list[i][j] = rgb[0] + "," + rgb[1] + "," + rgb[2];

}
}
return list;

}

/**
* 比较俩个图片的相似度
*
* @param image1
* @param image2
* @return
*/
public static float compareImage(File image1, File image2) {
String[][] list1 = getPX(image1);
String[][] list2 = getPX(image2);
int xiangsi = 0;
int busi = 0;
int i = 0, j = 0;
for (String[] strings : list1) {
if ((i + 1) == list1.length) {
continue;
}
for (int m = 0; m < strings.length; m++) {
try {
String[] value1 = list1[i][j].toString().split(",");
String[] value2 = list2[i][j].toString().split(",");
int k = 0;
for (int n = 0; n < value2.length; n++) {
if (Math.abs(Integer.parseInt(value1[k]) - Integer.parseInt(value2[k])) < 5) {
xiangsi++;
} else {
busi++;
}
}
} catch (RuntimeException e) {
continue;
}
j++;
}
i++;
}

list1 = getPX(image1);
list2 = getPX(image2);
i = 0;
j = 0;
for (String[] strings : list1) {
if ((i + 1) == list1.length) {
continue;
}
for (int m = 0; m < strings.length; m++) {
try {
String[] value1 = list1[i][j].toString().split(",");
String[] value2 = list2[i][j].toString().split(",");
int k = 0;
for (int n = 0; n < value2.length; n++) {
if (Math.abs(Integer.parseInt(value1[k]) - Integer.parseInt(value2[k])) < 5) {
xiangsi++;
} else {
busi++;
}
}
} catch (RuntimeException e) {
continue;
}
j++;
}
i++;
}
String baifen = "";
try {
baifen = ((Double.parseDouble(xiangsi + "") / Double.parseDouble((busi + xiangsi) + "")) + "");
baifen = baifen.substring(baifen.indexOf(".") + 1, baifen.indexOf(".") + 3);
} catch (Exception e) {
baifen = "0";
}
if (baifen.length() <= 0) {
baifen = "0";
}
if (busi == 0) {
baifen = "100";
}
logger.debug("相似像素数量:" + xiangsi + " 不相似像素数量:" + busi + " 相似率:" + Integer.parseInt(baifen) + "%");
return Integer.parseInt(baifen);


}
}

 

package com.opslab.util.image;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
* 图片相关的操作类
*/
public final class ImageUtil {

/**
* 重新设定图像的长高宽
* @param originalImage 图像数据
* @param width 宽
* @param height 高
* @return
*/
public static BufferedImage imageResize(BufferedImage originalImage, Integer width,Integer height){
if(width <= 0){
width =1;
}
if(height <= 0){
height =1;
}
BufferedImage newImage = new BufferedImage(width,height,originalImage.getType());
Graphics g = newImage.getGraphics();
g.drawImage(originalImage,0,0,width,height,null);
g.dispose();
return newImage;
}

/**
* 按照给点的比例放大图像
* 当缩减比例小于等于0时不发生任何变化
* @param originalImage 图像数据
* @param withdRatio 宽度缩减比例
* @param heightRatio 高度缩减比例
* @return 图像数据
*/
public static BufferedImage imageMagnifyRatio(BufferedImage originalImage, Integer withdRatio,Integer heightRatio){
if(withdRatio <= 0){
withdRatio =1;
}
if(heightRatio <= 0){
heightRatio =1;
}
int width = originalImage.getWidth()*withdRatio;
int height = originalImage.getHeight()*heightRatio;
BufferedImage newImage = new BufferedImage(width,height,originalImage.getType());
Graphics g = newImage.getGraphics();
g.drawImage(originalImage,0,0,width,height,null);
g.dispose();
return newImage;
}
/**
* 按照给点的比例缩小图像
* 当缩减比例小于等于0时不发生任何变化
* @param originalImage 图像数据
* @param withdRatio 宽度缩减比例
* @param heightRatio 高度缩减比例
* @return 图像数据
*/
public static BufferedImage imageShrinkRatio(BufferedImage originalImage, Integer withdRatio,Integer heightRatio){
if(withdRatio <= 0){
withdRatio =1;
}
if(heightRatio <= 0){
heightRatio =1;
}
int width = originalImage.getWidth()/withdRatio;
int height = originalImage.getHeight()/heightRatio;
BufferedImage newImage = new BufferedImage(width,height,originalImage.getType());
Graphics g = newImage.getGraphics();
g.drawImage(originalImage,0,0,width,height,null);
g.dispose();
return newImage;
}
}

 

 

package com.opslab.util.image;

import com.opslab.util.FileUtil;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.*;
import java.util.Iterator;
import java.util.List;

/**
* 图片相关的操作
* @author adam.胡升阳
*/
public final class OperateImage {
// 图形交换格式
public static String IMAGE_TYPE_GIF = "gif";
// 联合照片专家组
public static String IMAGE_TYPE_JPG = "jpg";
// 联合照片专家组
public static String IMAGE_TYPE_JPEG = "jpeg";
// 英文Bitmap(位图)的简写,它是Windows操作系统中的标准图像文件格式
public static String IMAGE_TYPE_BMP = "bmp";
// 可移植网络图形
public static String IMAGE_TYPE_PNG = "png";
// Photoshop的专用格式Photoshop
public static String IMAGE_TYPE_PSD = "psd";
/**
* 对图片裁剪,并把裁剪新图片保存
*
* @param srcPath 读取源图片路径
* @param toPath 写入图片路径
* @param x 剪切起始点x坐标
* @param y 剪切起始点y坐标
* @param width 剪切宽度
* @param height 剪切高度
* @param readImageFormat 读取图片格式
* @param writeImageFormat 写入图片格式
* @throws IOException
*/
public static void cropImage(String srcPath, String toPath,
int x, int y, int width, int height,
String readImageFormat, String writeImageFormat) throws IOException {
try(
FileInputStream fis =new FileInputStream(srcPath);
ImageInputStream iis = ImageIO.createImageInputStream(fis)
) {
Iterator it = ImageIO.getImageReadersByFormatName(readImageFormat);
ImageReader reader = (ImageReader) it.next();
//获取图片流
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
//定义一个矩形
Rectangle rect = new Rectangle(x, y, width, height);
//提供一个 BufferedImage,将其用作解码像素数据的目标。
param.setSourceRegion(rect);
BufferedImage bi = reader.read(0, param);
//保存新图片
ImageIO.write(bi, writeImageFormat, new File(toPath));
}catch (IOException e){
e.printStackTrace();
throw e;
}
}

/**
* 按倍率缩小图片
*
* @param srcImagePath 读取图片路径
* @param toImagePath 写入图片路径
* @param widthRatio 宽度缩小比例
* @param heightRatio 高度缩小比例
* @throws IOException
*/
public static void reduceImageByRatio(String srcImagePath, String toImagePath, int widthRatio, int heightRatio) throws IOException {
File file = new File(srcImagePath);
try(FileOutputStream out = new FileOutputStream(toImagePath)) {
//读入文件

String prefix= FileUtil.suffix(file);
// 构造Image对象
BufferedImage srcBuffer = ImageIO.read(file);
// 按比例缩减图像
BufferedImage imageBuffer = ImageUtil.imageShrinkRatio(srcBuffer, widthRatio, heightRatio);
ImageIO.write(imageBuffer,prefix,out);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 长高等比例缩小图片
*
* @param srcImagePath 读取图片路径
* @param toImagePath 写入图片路径
* @param ratio 缩小比例
* @throws IOException
*/
public static void reduceImageEqualProportion(String srcImagePath, String toImagePath, int ratio) throws IOException {
File file = new File(srcImagePath);
try(FileOutputStream out = new FileOutputStream(toImagePath)) {
//读入文件
String prefix= FileUtil.suffix(file);
// 构造Image对象
BufferedImage srcBuffer = ImageIO.read(file);
// 按比例缩减图像
BufferedImage imageBuffer = ImageUtil.imageShrinkRatio(srcBuffer, ratio, ratio);
ImageIO.write(imageBuffer,prefix,out);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 按倍率放大图片
*
* @param srcImagePath 读取图形路径
* @param toImagePath 写入入行路径
* @param widthRatio 宽度放大比例
* @param heightRatio 高度放大比例
* @throws IOException
*/
public static void enlargementImageByRatio(String srcImagePath, String toImagePath, int widthRatio, int heightRatio) throws IOException {
File file = new File(srcImagePath);
try(FileOutputStream out = new FileOutputStream(toImagePath)) {
//读入文件
String prefix= FileUtil.suffix(file);
// 构造Image对象
BufferedImage srcBuffer = ImageIO.read(file);
// 按比例缩减图像
BufferedImage imageBuffer = ImageUtil.imageMagnifyRatio(srcBuffer, widthRatio, heightRatio);
ImageIO.write(imageBuffer, prefix, out);
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 长高等比例放大图片
*
* @param srcImagePath 读取图形路径
* @param toImagePath 写入入行路径
* @param ratio 放大比例
* @throws IOException
*/
public static void enlargementImageEqualProportion(String srcImagePath, String toImagePath, int ratio) throws IOException {
File file = new File(srcImagePath);
try(FileOutputStream out = new FileOutputStream(toImagePath)) {
//读入文件
String prefix= FileUtil.suffix(file);
// 构造Image对象
BufferedImage srcBuffer = ImageIO.read(file);
// 按比例缩减图像
BufferedImage imageBuffer = ImageUtil.imageMagnifyRatio(srcBuffer, ratio, ratio);
ImageIO.write(imageBuffer, prefix, out);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 重置图形的边长大小
*
* @param srcImagePath 原图像
* @param toImagePath 新生产的图像
* @param width 图像宽度
* @param height 图像高度
* @throws IOException
*/
public static void resizeImage(String srcImagePath, String toImagePath, int width, int height) throws IOException {
File file = new File(srcImagePath);
try(FileOutputStream out = new FileOutputStream(toImagePath)) {
//读入文件
String prefix= FileUtil.suffix(file);
// 构造Image对象
BufferedImage srcBuffer = ImageIO.read(file);
// 按比例缩减图像
BufferedImage imageBuffer = ImageUtil.imageResize(srcBuffer, width, height);
ImageIO.write(imageBuffer, prefix, out);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 横向拼接图片(两张)
*
* @param firstSrcImagePath 第一张图片的路径
* @param secondSrcImagePath 第二张图片的路径
* @param imageFormat 拼接生成图片的格式
* @param toPath 拼接生成图片的路径
* 要拼接的俩张图片尺寸要一致
*/
public static void joinImagesHorizontal(String firstSrcImagePath, String secondSrcImagePath, String imageFormat, String toPath) {
try {
//读取第一张图片
File fileOne = new File(firstSrcImagePath);
BufferedImage imageOne = ImageIO.read(fileOne);
int width = imageOne.getWidth();//图片宽度
int height = imageOne.getHeight();//图片高度
//从图片中读取RGB
int[] imageArrayOne = new int[width * height];
imageArrayOne = imageOne.getRGB(0, 0, width, height, imageArrayOne, 0, width);

//对第二张图片做相同的处理
File fileTwo = new File(secondSrcImagePath);
BufferedImage imageTwo = ImageIO.read(fileTwo);
int width2 = imageTwo.getWidth();
int height2 = imageTwo.getHeight();
int[] ImageArrayTwo = new int[width2 * height2];
ImageArrayTwo = imageTwo.getRGB(0, 0, width, height, ImageArrayTwo, 0, width);
//ImageArrayTwo = imageTwo.getRGB(0,0,width2,height2,ImageArrayTwo,0,width2);

//生成新图片
//int height3 = (height>height2 || height==height2)?height:height2;
BufferedImage imageNew = new BufferedImage(width * 2, height, BufferedImage.TYPE_INT_RGB);
//BufferedImage imageNew = new BufferedImage(width+width2,height3,BufferedImage.TYPE_INT_RGB);
imageNew.setRGB(0, 0, width, height, imageArrayOne, 0, width);//设置左半部分的RGB
imageNew.setRGB(width, 0, width, height, ImageArrayTwo, 0, width);//设置右半部分的RGB
//imageNew.setRGB(width,0,width2,height2,ImageArrayTwo,0,width2);//设置右半部分的RGB

File outFile = new File(toPath);
ImageIO.write(imageNew, imageFormat, outFile);//写图片
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 横向拼接一组(多张)图像
*
* @param pics 将要拼接的图像
* @param type 图像写入格式
* @param dst_pic 图像写入路径
* @return
*/
public static boolean joinImageListHorizontal(String[] pics, String type, String dst_pic) {
try {
int len = pics.length;
if (len < 1) {
System.out.println("pics len < 1");
return false;
}
File[] src = new File[len];
BufferedImage[] images = new BufferedImage[len];
int[][] imageArrays = new int[len][];
for (int i = 0; i < len; i++) {
src[i] = new File(pics[i]);
images[i] = ImageIO.read(src[i]);
int width = images[i].getWidth();
int height = images[i].getHeight();
imageArrays[i] = new int[width * height];// 从图片中读取RGB
imageArrays[i] = images[i].getRGB(0, 0, width, height, imageArrays[i], 0, width);
}

int dst_width = 0;
int dst_height = images[0].getHeight();
for (int i = 0; i < images.length; i++) {
dst_height = dst_height > images[i].getHeight() ? dst_height : images[i].getHeight();
dst_width += images[i].getWidth();
}
//System.out.println(dst_width);
//System.out.println(dst_height);
if (dst_height < 1) {
System.out.println("dst_height < 1");
return false;
}
/*
* 生成新图片
*/
BufferedImage ImageNew = new BufferedImage(dst_width, dst_height, BufferedImage.TYPE_INT_RGB);
int width_i = 0;
for (int i = 0; i < images.length; i++) {
ImageNew.setRGB(width_i, 0, images[i].getWidth(), dst_height, imageArrays[i], 0, images[i].getWidth());
width_i += images[i].getWidth();
}
File outFile = new File(dst_pic);
ImageIO.write(ImageNew, type, outFile);// 写图片
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

/**
* 纵向拼接图片(两张)
*
* @param firstSrcImagePath 读取的第一张图片
* @param secondSrcImagePath 读取的第二张图片
* @param imageFormat 图片写入格式
* @param toPath 图片写入路径
*/
public static void joinImagesVertical(String firstSrcImagePath, String secondSrcImagePath, String imageFormat, String toPath) {
try {
//读取第一张图片
File fileOne = new File(firstSrcImagePath);
BufferedImage imageOne = ImageIO.read(fileOne);
int width = imageOne.getWidth();//图片宽度
int height = imageOne.getHeight();//图片高度
//从图片中读取RGB
int[] imageArrayOne = new int[width * height];
imageArrayOne = imageOne.getRGB(0, 0, width, height, imageArrayOne, 0, width);

//对第二张图片做相同的处理
File fileTwo = new File(secondSrcImagePath);
BufferedImage imageTwo = ImageIO.read(fileTwo);
int width2 = imageTwo.getWidth();
int height2 = imageTwo.getHeight();
int[] ImageArrayTwo = new int[width2 * height2];
ImageArrayTwo = imageTwo.getRGB(0, 0, width, height, ImageArrayTwo, 0, width);
//ImageArrayTwo = imageTwo.getRGB(0,0,width2,height2,ImageArrayTwo,0,width2);

//生成新图片
//int width3 = (width>width2 || width==width2)?width:width2;
BufferedImage imageNew = new BufferedImage(width, height * 2, BufferedImage.TYPE_INT_RGB);
//BufferedImage imageNew = new BufferedImage(width3,height+height2,BufferedImage.TYPE_INT_RGB);
imageNew.setRGB(0, 0, width, height, imageArrayOne, 0, width);//设置上半部分的RGB
imageNew.setRGB(0, height, width, height, ImageArrayTwo, 0, width);//设置下半部分的RGB
//imageNew.setRGB(0,height,width2,height2,ImageArrayTwo,0,width2);//设置下半部分的RGB

File outFile = new File(toPath);
ImageIO.write(imageNew, imageFormat, outFile);//写图片
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 纵向拼接一组(多张)图像
*
* @param pics 将要拼接的图像数组
* @param type 写入图像类型
* @param dst_pic 写入图像路径
* @return
*/
public static boolean joinImageListVertical(String[] pics, String type, String dst_pic) {
try {
int len = pics.length;
if (len < 1) {
System.out.println("pics len < 1");
return false;
}
File[] src = new File[len];
BufferedImage[] images = new BufferedImage[len];
int[][] imageArrays = new int[len][];
for (int i = 0; i < len; i++) {
//System.out.println(i);
src[i] = new File(pics[i]);
images[i] = ImageIO.read(src[i]);
int width = images[i].getWidth();
int height = images[i].getHeight();
imageArrays[i] = new int[width * height];// 从图片中读取RGB
imageArrays[i] = images[i].getRGB(0, 0, width, height, imageArrays[i], 0, width);
}

int dst_height = 0;
int dst_width = images[0].getWidth();
for (int i = 0; i < images.length; i++) {
dst_width = dst_width > images[i].getWidth() ? dst_width : images[i].getWidth();
dst_height += images[i].getHeight();
}
//System.out.println(dst_width);
//System.out.println(dst_height);
if (dst_height < 1) {
System.out.println("dst_height < 1");
return false;
}
/*
* 生成新图片
*/
BufferedImage ImageNew = new BufferedImage(dst_width, dst_height, BufferedImage.TYPE_INT_RGB);
int height_i = 0;
for (int i = 0; i < images.length; i++) {
ImageNew.setRGB(0, height_i, dst_width, images[i].getHeight(), imageArrays[i], 0, dst_width);
height_i += images[i].getHeight();
}
File outFile = new File(dst_pic);
ImageIO.write(ImageNew, type, outFile);// 写图片
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

/**
* 合并图片(按指定初始x、y坐标将附加图片贴到底图之上)
*
* @param negativeImagePath 背景图片路径
* @param additionImagePath 附加图片路径
* @param x 附加图片的起始点x坐标
* @param y 附加图片的起始点y坐标
* @param toPath 图片写入路径
* @throws IOException
*/
public static void mergeBothImage(String negativeImagePath, String additionImagePath,String iamgeFromat, int x, int y, String toPath) throws IOException {
InputStream is = null;
InputStream is2 = null;
OutputStream os = null;
try {
is = new FileInputStream(negativeImagePath);
is2 = new FileInputStream(additionImagePath);
BufferedImage image = ImageIO.read(is);
BufferedImage image2 = ImageIO.read(is2);
Graphics g = image.getGraphics();
g.drawImage(image2, x, y, null);
os = new FileOutputStream(toPath);
ImageIO.write(image, iamgeFromat, os);//写图片
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
os.close();
}
if (is2 != null) {
is2.close();
}
if (is != null) {
is.close();
}
}
}

/**
* 将一组图片一次性附加合并到底图上
*
* @param negativeImagePath 源图像(底图)路径
* @param additionImageList 附加图像信息列表
* @param imageFormat 图像写入格式
* @param toPath 图像写入路径
* @throws IOException
*/
public static void mergeImageList(String negativeImagePath, List additionImageList, String imageFormat, String toPath) throws IOException {
InputStream is = null;
InputStream is2 = null;
OutputStream os = null;
try {
is = new FileInputStream(negativeImagePath);
BufferedImage image = ImageIO.read(is);
//Graphics g=image.getGraphics();
Graphics2D g = image.createGraphics();
BufferedImage image2 = null;
if (additionImageList != null) {
for (int i = 0; i < additionImageList.size(); i++) {
//解析附加图片信息:x坐标、 y坐标、 additionImagePath附加图片路径
//图片信息存储在一个数组中
String[] additionImageInfo = (String[]) additionImageList.get(i);
int x = Integer.parseInt(additionImageInfo[0]);
int y = Integer.parseInt(additionImageInfo[1]);
String additionImagePath = additionImageInfo[2];
//读取文件输入流,并合并图片
is2 = new FileInputStream(additionImagePath);
//System.out.println(x+" : "+y+" : "+additionImagePath);
image2 = ImageIO.read(is2);
g.drawImage(image2, x, y, null);
}
}
os = new FileOutputStream(toPath);
ImageIO.write(image, imageFormat, os);//写图片
//JPEGImageEncoder enc=JPEGCodec.createJPEGEncoder(os);
//enc.encode(image);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
os.close();
}
if (is2 != null) {
is2.close();
}
if (is != null) {
is.close();
}
}
}

 

 

 

 

 


/**
* 图片灰化操作
*
* @param srcImage 读取图片路径
* @param toPath 写入灰化后的图片路径
* @param imageFormat 图片写入格式
*/
public static void grayImage(String srcImage, String toPath, String imageFormat) {
try {
BufferedImage src = ImageIO.read(new File(srcImage));
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
src = op.filter(src, null);
ImageIO.write(src, imageFormat, new File(toPath));
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 在源图片上设置水印文字
*
* @param srcImagePath 源图片路径
* @param alpha 透明度(0<alpha<1)
* @param font 字体(例如:宋体)
* @param fontStyle 字体格式(例如:普通样式--Font.PLAIN、粗体--Font.BOLD )
* @param fontSize 字体大小
* @param color 字体颜色(例如:黑色--Color.BLACK)
* @param inputWords 输入显示在图片上的文字
* @param x 文字显示起始的x坐标
* @param y 文字显示起始的y坐标
* @param imageFormat 写入图片格式(png/jpg等)
* @param toPath 写入图片路径
* @throws IOException
*/
public static void alphaWords2Image(String srcImagePath, float alpha,
String font, int fontStyle, int fontSize, Color color,
String inputWords, int x, int y, String imageFormat, String toPath) throws IOException {
FileOutputStream fos = null;
try {
BufferedImage image = ImageIO.read(new File(srcImagePath));
//创建java2D对象
Graphics2D g2d = image.createGraphics();
//用源图像填充背景
g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null, null);
//设置透明度
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
g2d.setComposite(ac);
//设置文字字体名称、样式、大小
g2d.setFont(new Font(font, fontStyle, fontSize));
g2d.setColor(color);//设置字体颜色
g2d.drawString(inputWords, x, y); //输入水印文字及其起始x、y坐标
g2d.dispose();
fos = new FileOutputStream(toPath);
ImageIO.write(image, imageFormat, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}

/**
* 在源图像上设置图片水印
* ---- 当alpha==1时文字不透明(和在图片上直接输入文字效果一样)
*
* @param srcImagePath 源图片路径
* @param appendImagePath 水印图片路径
* @param alpha 透明度
* @param x 水印图片的起始x坐标
* @param y 水印图片的起始y坐标
* @param width 水印图片的宽度
* @param height 水印图片的高度
* @param imageFormat 图像写入图片格式
* @param toPath 图像写入路径
* @throws IOException
*/
public static void alphaImage2Image(String srcImagePath, String appendImagePath,
float alpha, int x, int y, int width, int height,
String imageFormat, String toPath) throws IOException {
FileOutputStream fos = null;
try {
BufferedImage image = ImageIO.read(new File(srcImagePath));
//创建java2D对象
Graphics2D g2d = image.createGraphics();
//用源图像填充背景
g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null, null);
//设置透明度
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
g2d.setComposite(ac);
//设置水印图片的起始x/y坐标、宽度、高度
BufferedImage appendImage = ImageIO.read(new File(appendImagePath));
g2d.drawImage(appendImage, x, y, width, height, null, null);
g2d.dispose();
fos = new FileOutputStream(toPath);
ImageIO.write(image, imageFormat, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}

/**
* 画单点 ---- 实际上是画一个填充颜色的圆
* ---- 以指定点坐标为中心画一个小半径的圆形,并填充其颜色来充当点
*
* @param srcImagePath 源图片颜色
* @param x 点的x坐标
* @param y 点的y坐标
* @param width 填充的宽度
* @param height 填充的高度
* @param ovalColor 填充颜色
* @param imageFormat 写入图片格式
* @param toPath 写入路径
* @throws IOException
*/
public static void drawPoint(String srcImagePath, int x, int y, int width, int height, Color ovalColor, String imageFormat, String toPath) throws IOException {
FileOutputStream fos = null;
try {
//获取源图片
BufferedImage image = ImageIO.read(new File(srcImagePath));
//根据xy点坐标绘制连接线
Graphics2D g2d = image.createGraphics();
g2d.setColor(ovalColor);
//填充一个椭圆形
g2d.fillOval(x, y, width, height);
fos = new FileOutputStream(toPath);
ImageIO.write(image, imageFormat, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}

/**
* 画一组(多个)点---- 实际上是画一组(多个)填充颜色的圆
* ---- 以指定点坐标为中心画一个小半径的圆形,并填充其颜色来充当点
*
* @param srcImagePath 原图片路径
* @param pointList 点列表
* @param width 宽度
* @param height 高度
* @param ovalColor 填充颜色
* @param imageFormat 写入图片颜色
* @param toPath 写入路径
* @throws IOException
*/
public static void drawPoints(String srcImagePath, List pointList, int width, int height, Color ovalColor, String imageFormat, String toPath) throws IOException {
FileOutputStream fos = null;
try {
//获取源图片
BufferedImage image = ImageIO.read(new File(srcImagePath));
//根据xy点坐标绘制连接线
Graphics2D g2d = image.createGraphics();
g2d.setColor(ovalColor);
//填充一个椭圆形
if (pointList != null) {
for (int i = 0; i < pointList.size(); i++) {
Point point = (Point) pointList.get(i);
int x = (int) point.getX();
int y = (int) point.getY();
g2d.fillOval(x, y, width, height);
}
}
fos = new FileOutputStream(toPath);
ImageIO.write(image, imageFormat, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}

/**
* 画线段
*
* @param srcImagePath 源图片路径
* @param x1 第一个点x坐标
* @param y1 第一个点y坐标
* @param x2 第二个点x坐标
* @param y2 第二个点y坐标
* @param lineColor 线条颜色
* @param toPath 图像写入路径
* @param imageFormat 图像写入格式
* @throws IOException
*/
public static void drawLine(String srcImagePath, int x1, int y1, int x2, int y2, Color lineColor, String toPath, String imageFormat) throws IOException {
FileOutputStream fos = null;
try {
//获取源图片
BufferedImage image = ImageIO.read(new File(srcImagePath));
//根据xy点坐标绘制连接线
Graphics2D g2d = image.createGraphics();
g2d.setColor(lineColor);
g2d.drawLine(x1, y1, x2, y2);
fos = new FileOutputStream(toPath);
ImageIO.write(image, imageFormat, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}

/**
* 画折线 / 线段
* ---- 2个点即画线段,多个点画折线
*
* @param srcImagePath 源图片路径
* @param xPoints x坐标数组
* @param yPoints y坐标数组
* @param nPoints 点的数量
* @param lineColor 线条颜色
* @param toPath 图像写入路径
* @param imageFormat 图片写入格式
* @throws IOException
*/
public static void drawPolyline(String srcImagePath, int[] xPoints, int[] yPoints, int nPoints, Color lineColor, String toPath, String imageFormat) throws IOException {
FileOutputStream fos = null;
try {
//获取源图片
BufferedImage image = ImageIO.read(new File(srcImagePath));
//根据xy点坐标绘制连接线
Graphics2D g2d = image.createGraphics();
//设置线条颜色
g2d.setColor(lineColor);
g2d.drawPolyline(xPoints, yPoints, nPoints);
//图像写出路径
fos = new FileOutputStream(toPath);
ImageIO.write(image, imageFormat, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}

/**
* 绘制折线,并突出显示转折点
*
* @param srcImagePath 源图片路径
* @param xPoints x坐标数组
* @param yPoints y坐标数组
* @param nPoints 点的数量
* @param lineColor 连线颜色
* @param width 点的宽度
* @param height 点的高度
* @param ovalColor 点的填充颜色
* @param toPath 图像写入路径
* @param imageFormat 图像写入格式
* @throws IOException
*/
public static void drawPolylineShowPoints(String srcImagePath, int[] xPoints, int[] yPoints, int nPoints, Color lineColor, int width, int height, Color ovalColor, String toPath, String imageFormat) throws IOException {
FileOutputStream fos = null;
try {
//获取源图片
BufferedImage image = ImageIO.read(new File(srcImagePath));
//根据xy点坐标绘制连接线
Graphics2D g2d = image.createGraphics();
//设置线条颜色
g2d.setColor(lineColor);
//画线条
g2d.drawPolyline(xPoints, yPoints, nPoints);
//设置圆点颜色
g2d.setColor(ovalColor);
//画圆点
if (xPoints != null) {
for (int i = 0; i < xPoints.length; i++) {
int x = xPoints[i];
int y = yPoints[i];
g2d.fillOval(x, y, width, height);
}
}
//图像写出路径
fos = new FileOutputStream(toPath);
ImageIO.write(image, imageFormat, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}


/**
* 绘制一个由 x 和 y 坐标数组定义的闭合多边形
*
* @param srcImagePath 源图片路径
* @param xPoints x坐标数组
* @param yPoints y坐标数组
* @param nPoints 坐标点的个数
* @param polygonColor 线条颜色
* @param imageFormat 图像写入格式
* @param toPath 图像写入路径
* @throws IOException
*/
public static void drawPolygon(String srcImagePath, int[] xPoints, int[] yPoints, int nPoints, Color polygonColor, String imageFormat, String toPath) throws IOException {
FileOutputStream fos = null;
try {
//获取图片
BufferedImage image = ImageIO.read(new File(srcImagePath));
//根据xy点坐标绘制闭合多边形
Graphics2D g2d = image.createGraphics();
g2d.setColor(polygonColor);
g2d.drawPolygon(xPoints, yPoints, nPoints);
fos = new FileOutputStream(toPath);
ImageIO.write(image, imageFormat, fos);
g2d.dispose();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}

/**
* 绘制并填充多边形
*
* @param srcImagePath 源图像路径
* @param xPoints x坐标数组
* @param yPoints y坐标数组
* @param nPoints 坐标点个数
* @param polygonColor 多边形填充颜色
* @param alpha 多边形部分透明度
* @param imageFormat 写入图形格式
* @param toPath 写入图形路径
* @throws IOException
*/
public static void drawAndAlphaPolygon(String srcImagePath, int[] xPoints, int[] yPoints, int nPoints, Color polygonColor, float alpha, String imageFormat, String toPath) throws IOException {
FileOutputStream fos = null;
try {
//获取图片
BufferedImage image = ImageIO.read(new File(srcImagePath));
//根据xy点坐标绘制闭合多边形
Graphics2D g2d = image.createGraphics();
g2d.setColor(polygonColor);
//设置透明度
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
g2d.setComposite(ac);
g2d.fillPolygon(xPoints, yPoints, nPoints);
fos = new FileOutputStream(toPath);
ImageIO.write(image, imageFormat, fos);
g2d.dispose();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}

}

posted on 2019-01-11 13:51  我是司  阅读(135)  评论(0)    收藏  举报

导航