2018년 7월 12일 목요일

[Java] Time string parsing and formatting


1. LocalDateTime parsing and formatting examples

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public static LocalDateTime parseTime(String timeStr, String format) {
    return LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern(format));
}

static String formatTime(LocalDateTime time, String format) {
    return DateTimeFormatter.ofPattern(format).format(time); 
}

static String formatTime2(LocalDateTime time, String format) {
    return time.format(DateTimeFormatter.ofPattern(format)); 
}
  
public static void main(String[] args) {
    LocalDateTime time = parseTime( "2018-08-21 21:45:31", "yyyy-MM-dd HH:mm:ss");
    String timeStr = formatTime(time, "yyyyMMdd_HHmmss");
    String timeStr2 = formatTime2(time, "yyyyMMdd_HHmmss");
    System.out.println(time);
    System.out.println(timeStr);
    System.out.println(timeStr2);
}


Output:
2018-08-21T21:45:31
20180821_214531
20180821_214531



2. Date and Time Format
Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   G       era                         text              AD; Anno Domini; A
   u       year                        year              2004; 04
   y       year-of-era                 year              2004; 04
   D       day-of-year                 number            189
   M/L     month-of-year               number/text       7; 07; Jul; July; J
   d       day-of-month                number            10

   Q/q     quarter-of-year             number/text       3; 03; Q3; 3rd quarter
   Y       week-based-year             year              1996; 96
   w       week-of-week-based-year     number            27
   W       week-of-month               number            4
   E       day-of-week                 text              Tue; Tuesday; T
   e/c     localized day-of-week       number/text       2; 02; Tue; Tuesday; T
   F       week-of-month               number            3

   a       am-pm-of-day                text              PM
   h       clock-hour-of-am-pm (1-12)  number            12
   K       hour-of-am-pm (0-11)        number            0
   k       clock-hour-of-am-pm (1-24)  number            0

   H       hour-of-day (0-23)          number            0
   m       minute-of-hour              number            30
   s       second-of-minute            number            55
   S       fraction-of-second          fraction          978
   A       milli-of-day                number            1234
   n       nano-of-second              number            987654321
   N       nano-of-day                 number            1234000000

   V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
   z       time-zone name              zone-name         Pacific Standard Time; PST
   O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
   x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15;
   Z       zone-offset                 offset-Z          +0000; -0800; -08:00;

   p       pad next                    pad modifier      1

   '       escape for text             delimiter
   ''      single quote                literal           '
   [       optional section start
   ]       optional section end
   #       reserved for future use
   {       reserved for future use
   }       reserved for future use
 


3. Predefined Formatters
FormatterDescriptionExample
ofLocalizedDate(dateStyle)Formatter with date style from the locale'2011-12-03'
ofLocalizedTime(timeStyle)Formatter with time style from the locale'10:15:30'
ofLocalizedDateTime(dateTimeStyle)Formatter with a style for date and time from the locale'3 Jun 2008 11:05:30'
ofLocalizedDateTime(dateStyle,timeStyle)Formatter with date and time styles from the locale'3 Jun 2008 11:05'
BASIC_ISO_DATEBasic ISO date'20111203'
ISO_LOCAL_DATEISO Local Date'2011-12-03'
ISO_OFFSET_DATEISO Date with offset'2011-12-03+01:00'
ISO_DATEISO Date with or without offset'2011-12-03+01:00'; '2011-12-03'
ISO_LOCAL_TIMETime without offset'10:15:30'
ISO_OFFSET_TIMETime with offset'10:15:30+01:00'
ISO_TIMETime with or without offset'10:15:30+01:00'; '10:15:30'
ISO_LOCAL_DATE_TIMEISO Local Date and Time'2011-12-03T10:15:30'
ISO_OFFSET_DATE_TIMEDate Time with Offset2011-12-03T10:15:30+01:00'
ISO_ZONED_DATE_TIMEZoned Date Time'2011-12-03T10:15:30+01:00[Europe/Paris]'
ISO_DATE_TIMEDate and time with ZoneId'2011-12-03T10:15:30+01:00[Europe/Paris]'
ISO_ORDINAL_DATEYear and day of year'2012-337'
ISO_WEEK_DATEYear and Week2012-W48-6'
ISO_INSTANTDate and Time of an Instant'2011-12-03T10:15:30Z'
RFC_1123_DATE_TIMERFC 1123 / RFC 822'Tue, 3 Jun 2008 11:05:30 GMT'





2018년 7월 8일 일요일

[Java] PDF Creation with iText


Download: iText 4.2.1

1. Document Open
1
2
3
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
document.open();


2. Document Close
1
document.close();


3. Add Page
1
document.newPage();


4. Add Text
1
document.add(new Paragraph("Hello World"));


5. Add Image
1
2
3
4
5
Image jpg = Image.getInstance("a.jpg");
jpg.setBorder(Image.BOX);
jpg.setBorderColor( new Color(0xFF, 0x00, 0xff));
jpg.setBorderWidth(5);
document.add(jpg);

1
2
3
4
5
6
7
8
Image png = Image.getInstance("a.png");
png.setBorder(Image.BOX);
png.setBorderColor( new Color(0xFF, 0x00, 0xff));
png.setBorderWidth(5);
//Rectangle r = document.getPageSize();
//png.scaleAbsoluteWidth(r.getWidth());
png.scalePercent(50);
document.add(png);


6. Add Table
1
2
3
4
5
6
7
8
9
PdfPTable table = new PdfPTable(10);
for (int k = 1; k <= 100; ++k) {
	table.addCell("number " + k);
}
table.setTotalWidth(800);
table.writeSelectedRows(0, 5, 0, -1, 50, 650, writer.getDirectContent());
document.newPage();
table.writeSelectedRows(5, -1, 0, -1, 50, 650, writer.getDirectContent());	    
document.newPage();

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
PdfPTable datatable = new PdfPTable(10);
int headerwidths[] = { 10, 24, 12, 12, 7, 7, 7, 7, 7, 7 };
datatable.setWidths(headerwidths);
datatable.setWidthPercentage(100);
datatable.getDefaultCell().setPadding(5);

datatable.setHeaderRows(2);

datatable.getDefaultCell().setBorderWidth(1);
for (int i = 1; i < 30; i++) {
	datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
	PdfPCell h = new PdfPCell(new Paragraph("myUserId"));
	h.setGrayFill(0.7f);;
	h.setImage(png);
	datatable.addCell(h);;
	//datatable.addCell("myUserId");
	datatable.addCell("long long name");
	datatable.addCell("No Name Company");
	datatable.addCell("D" + i);
	datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
	for (int j = 0; j < 6; j++)
		datatable.addCell(Math.random() > .5 ? "Yes" : "No");
}
datatable.setSplitLate(false);
document.add(datatable);


7. Add Outline
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
PdfOutline rootOutline = writer.getRootOutline();	    
writer.setPageEmpty(true);

document.newPage();
writer.setPageEmpty(false);

document.newPage();
PdfOutline helloBookmark = new PdfOutline(rootOutline, 
	new PdfDestination( PdfDestination.FITH, writer.getVerticalPosition(true)),
	"Hello World", true);    
document.add(new Paragraph("Hello World"));

document.newPage();
PdfOutline link = new PdfOutline(helloBookmark, 
	new PdfDestination( PdfDestination.FITH, writer.getVerticalPosition(true)),
	"Next World");
document.add(new Paragraph("Next World"));


8. Add Chapter
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
document.open();
Paragraph hello = new Paragraph("hello, ");
Chapter universe = new Chapter("A", 1);
Section section;
section = universe.addSection("B");
section.add(hello);
document.add(universe);
Chapter people = new Chapter("C", 2);
section = people.addSection("D");
section.add(hello);
document.add(people);
document.setPageSize(PageSize.A4.rotate());
Chapter animals = new Chapter("E", 4);
section = animals.addSection("F");
section.add(hello);
document.add(animals);
document.close();


9. Add Chapter with Auto Number

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
document.open();
Phrase text = new Phrase("test. ");
ChapterAutoNumber chapter1 = new ChapterAutoNumber("This is a sample sentence:");
chapter1.setBookmarkTitle("The fox");
chapter1.setBookmarkOpen(false);
Section section1 = chapter1.addSection("Quick");
section1.add(text);
document.add(chapter1);
ChapterAutoNumber chapter2 = new ChapterAutoNumber("Jumps");
Section section = chapter2.addSection("Over");
section.add(text);
document.add(chapter2);
document.close();





















[Java] Image Processing with ImageJ


Download: ij152.zip


1. Image Create and Save
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public static void createJpegImage(int width, int height) {
    ImagePlus imp = IJ.createImage("created.jpg", "jpg", width, height, 32);
    ImageProcessor ip = imp.getProcessor();
    ip.setColor(Color.BLUE);
    ip.setLineWidth(4);
    ip.drawRect(10, 10, imp.getWidth() - 20, imp.getHeight() - 20); 
    IJ.save(imp, "D:/created.jpg");
    /* extension: 
     * ".tif", ".jpg", ".gif", ".zip", ".raw", ".avi", ".bmp",
     * ".fits", ".pgm", ".png", ".lut", ".roi", ".txt"
     */
    //imp.show();
}

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public static void createJpegImage2(int width, int height) {
    ImagePlus imp = IJ.createImage("created.jpg", "jpg", width, height, 32);
    ImageProcessor ip = imp.getProcessor();
    ip.setColor(Color.BLUE);
    ip.setLineWidth(4);
    ip.drawRect(10, 10, imp.getWidth() - 20, imp.getHeight() - 20); 
    IJ.saveAs(imp, "jpeg","D:/created.jpg");
    /* type:
     * "tiff", "jpeg", "gif", "zip", "raw", "avi", "bmp", "fits", "pgm", 
     * "png", "text image", "lut", "text"
     */
}


Output: D:\created.jpg



2. Image Load and Convert To Gray Scale
1
2
3
4
5
6
7
public static void convertToGray() {
    ImagePlus ip = IJ.openImage("D:/lena.png");
    ImageConverter ic = new ImageConverter(ip);
    FileSaver fs = new FileSaver(ip);
    ic.convertToGray8();
    fs.saveAsJpeg("D:/lena_gray.jpg");
}

Input: lena.png


Output: lena_gray.jpg



3. Image Convert to Jpeg
1
2
3
4
5
6
7
public static void convertToJpeg(int quality) {
    ImagePlus ip = IJ.openImage("D:/lena.png");
    FileSaver fs = new FileSaver(ip);
    FileSaver.setJpegQuality(quality);
    FileSaver.getJpegQuality();
    fs.saveAsJpeg("D:/lena.jpg");
}


4. Image Resize

4.1 ImagResize by Width (with the aspect ratio maintained)
1
2
3
4
5
6
7
8
public static void resizeImage() {
    ImagePlus imp = IJ.openImage("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    ip = ip.resize(imp.getWidth()/2);
    imp.setProcessor(ip);
    FileSaver fs = new FileSaver(imp);
    fs.saveAsPng("D:/lena_half.png");
}


4.2 Image Resize by Width and Height
1
2
3
4
5
6
7
public static void resizeImage2() {
    ImagePlus imp = IJ.openImage("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    ip = ip.resize(imp.getWidth(),imp.getHeight()/2);
    imp.setProcessor(ip);
    IJ.save(imp,"D:/lena_resized.png");
}

Output: lena_resized.png



4.3 Image Rescale
1
2
3
4
5
6
public static void rescaleImage() {
    ImagePlus imp = IJ.openImage("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    ip.scale(1.0,0.5); //xScale, yScale
    IJ.save(imp,"D:/lena_rescaled.png");
}

Output: lena_rescaled.png (image size is not changed)



5. Image Crop
1
2
3
4
5
6
7
8
9
public static void cropImage() {
    ImagePlus imp = IJ.openImage("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    ip.setRoi(0, 0, imp.getWidth()/2, imp.getHeight()/2); //x, y, w, h
    ip = ip.crop();
    imp.setProcessor(ip);
    FileSaver fs = new FileSaver(imp);
    fs.saveAsPng("D:/lena_crop.png");
}

Output: lena_crop.jpg



6. Image Smooth
1
2
3
4
5
6
7
public static void smoothImage() {
    ImagePlus imp = IJ.openImage("D:/lena.png");
    for( int i=0; i < 10; i++ ) 
        imp.getProcessor().smooth();
    FileSaver fs = new FileSaver(imp);
    fs.saveAsPng("D:/lena_smooth.png");
}

Input: lena.png


Output: lena_smooth.png




7. Image Rotate

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public static void rotateImage() {
    ImagePlus imp = IJ.openImage("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    ImageProcessor ip_left = ip.rotateLeft();
    ImageProcessor ip_right = ip.rotateRight();
    imp.setProcessor(ip_left);
    IJ.save(imp,"D:/lena_left.png");
    imp.setProcessor(ip_right);
    IJ.save(imp,"D:/lena_right.png");
    ip.rotate(45);
    imp.setProcessor(ip);
    IJ.save(imp,"D:/lena_rotated.png");
}


Input: lena.png


Output: lena_left.png


Output: lena_right.png


Output: lena_rotated.png




8. Image Overlay
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public static void overlayImage() {
    
    ImagePlus imp = new ImagePlus("D:/lena.png");
    BufferedImage bi = imp.getBufferedImage();
    
    ImagePlus imp2 = imp.duplicate();
    imp2.setProcessor(imp2.getProcessor().resize(imp2.getWidth()/2));
    new ImageConverter(imp2).convertToGray8();
    BufferedImage bi2 = imp2.getBufferedImage();
    
    Graphics2D g = bi.createGraphics();
    g.drawImage(bi2, 0, 0, null);
    ImagePlus imp3 = new ImagePlus("combined", bi);
    FileSaver fs = new FileSaver(imp3);
    fs.saveAsJpeg("D:/lena_overlay.jpg");       
}


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public static void overlayImage2() {
    
    ImagePlus imp = new ImagePlus("D:/lena.png");
    BufferedImage bi = imp.getBufferedImage();
    
    ImagePlus imp2 = imp.duplicate();
    imp2.setProcessor(imp2.getProcessor().resize(imp2.getWidth()/2));
    new ImageConverter(imp2).convertToGray8();
    BufferedImage bi2 = imp2.getBufferedImage();

    BufferedImage combined = new BufferedImage(imp.getWidth(), imp.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = combined.createGraphics();
    g.drawImage(bi, 0, 0, null);
    g.drawImage(bi2, 0, 0, null);
    ImagePlus imp3 = new ImagePlus("combined", combined);
    FileSaver fs = new FileSaver(imp3);
    fs.saveAsJpeg("D:/lena_overlay2.jpg");       
}


Input: lena.png

output: lena_overlay.png




9. Image Partial Edit
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public static void grayPartialImage() {
    ImagePlus imp = new ImagePlus("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    BufferedImage bufferedImage = imp.getBufferedImage();
    for(int y=0; y < bufferedImage.getHeight()/2; y++) {
        for(int x=0; x < bufferedImage.getWidth()/2; x++) {
            Color color = new Color(bufferedImage.getRGB(x, y));
            int grayLevel = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
            int r = grayLevel;
            int g = grayLevel;
            int b = grayLevel;
            int rgb = (r << 16) | (g << 8) | b;
            bufferedImage.setRGB(x, y, rgb);
        }
    }
    ImagePlus grayImg = new ImagePlus("gray", bufferedImage);
    FileSaver fs = new FileSaver(grayImg);
    fs.saveAsJpeg("D:/lena_partial.jpg");       
}

Output:: lena_partial.jpg





1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public static void clearPartialImage() {
    ImagePlus imp = new ImagePlus("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    BufferedImage bufferedImage = imp.getBufferedImage();
    for(int y=0; y < bufferedImage.getHeight()/2; y++) {
        for(int x=0; x < bufferedImage.getWidth()/2; x++) {
            int rgb = 0x00ffffff;
            bufferedImage.setRGB(x, y, rgb);
        }
    }
    ImagePlus grayImg = new ImagePlus("gray", bufferedImage);
    FileSaver fs = new FileSaver(grayImg);
    fs.saveAsJpeg("D:/lena_white.jpg");       
}

Output: lena_white.jpg