服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

用java实现print screen,读取位图文件,将位图文件转化位jpeg格式并保存成文件输出!

package screensaver;
import java.awt.*;
import java.awt.image.bufferedimage;
import java.io.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import java.awt.image;
import java.awt.toolkit;
import java.awt.image.bufferedimage;
import java.awt.image.memoryimagesource;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import com.sun.image.codec.jpeg.jpegcodec;
import com.sun.image.codec.jpeg.jpegimageencoder;
public class screenpicsaver
{
  mediatracker tracker = new mediatracker(new component()
  {});
  public screenpicsaver()
  {}
  public image loadbitmap(string sdir, string sfile) //读取8位或24位的位图文件
  {
    image image;
    system.out.println("loading:" + sdir + sfile);
    try
    {
      fileinputstream fs = new fileinputstream(sdir + sfile);
      int bflen = 14; // 14 字节 bitmapfileheader
      byte bf[] = new byte[bflen];
      fs.read(bf, 0, bflen);
      int bilen = 40; // 40 字节 bitmapinfoheader
      byte bi[] = new byte[bilen];
      fs.read(bi, 0, bilen);
      // 解释数据。
      int nsize = ( ( (int) bf[5] & 0xff) << 24)
          | ( ( (int) bf[4] & 0xff) << 16)
          | ( ( (int) bf[3] & 0xff) << 8)
          | (int) bf[2] & 0xff;
      system.out.println("file type is :" + (char) bf[0] + (char) bf[1]);
      system.out.println("size of file is :" + nsize);
      int nbisize = ( ( (int) bi[3] & 0xff) << 24)
          | ( ( (int) bi[2] & 0xff) << 16)
          | ( ( (int) bi[1] & 0xff) << 8)
          | (int) bi[0] & 0xff;
      system.out.println("size of bitmapinfoheader is :" + nbisize);
      int nwidth = ( ( (int) bi[7] & 0xff) << 24)
          | ( ( (int) bi[6] & 0xff) << 16)
          | ( ( (int) bi[5] & 0xff) << 8)
          | (int) bi[4] & 0xff;
      system.out.println("width is :" + nwidth);
      int nheight = ( ( (int) bi[11] & 0xff) << 24)
          | ( ( (int) bi[10] & 0xff) << 16)
          | ( ( (int) bi[9] & 0xff) << 8)
          | (int) bi[8] & 0xff;
      system.out.println("height is :" + nheight);
      int nplanes = ( ( (int) bi[13] & 0xff) << 8) | (int) bi[12] & 0xff;
      system.out.println("planes is :" + nplanes);
      int nbitcount = ( ( (int) bi[15] & 0xff) << 8) | (int) bi[14] & 0xff;
      system.out.println("bitcount is :" + nbitcount);
      // 查找表明压缩的非零值
      int ncompression = ( ( (int) bi[19]) << 24)
          | ( ( (int) bi[18]) << 16)
          | ( ( (int) bi[17]) << 8)
          | (int) bi[16];
      system.out.println("compression is :" + ncompression);
      int nsizeimage = ( ( (int) bi[23] & 0xff) << 24)
          | ( ( (int) bi[22] & 0xff) << 16)
          | ( ( (int) bi[21] & 0xff) << 8)
          | (int) bi[20] & 0xff;
      system.out.println("sizeimage is :" + nsizeimage);
      int nxpm = ( ( (int) bi[27] & 0xff) << 24)
          | ( ( (int) bi[26] & 0xff) << 16)
          | ( ( (int) bi[25] & 0xff) << 8)
          | (int) bi[24] & 0xff;
      system.out.println("x-pixels per meter is :" + nxpm);
      int nypm = ( ( (int) bi[31] & 0xff) << 24)
          | ( ( (int) bi[30] & 0xff) << 16)
          | ( ( (int) bi[29] & 0xff) << 8)
          | (int) bi[28] & 0xff;
      system.out.println("y-pixels per meter is :" + nypm);
      int nclrused = ( ( (int) bi[35] & 0xff) << 24)
          | ( ( (int) bi[34] & 0xff) << 16)
          | ( ( (int) bi[33] & 0xff) << 8)
          | (int) bi[32] & 0xff;
      system.out.println("colors used are :" + nclrused);
      int nclrimp = ( ( (int) bi[39] & 0xff) << 24)
          | ( ( (int) bi[38] & 0xff) << 16)
          | ( ( (int) bi[37] & 0xff) << 8)
          | (int) bi[36] & 0xff;
      system.out.println("colors important are :" + nclrimp);
      if (nbitcount == 24)
      {
        // 24 位格式不包含调色板数据,但扫描行被补足到
        // 4 个字节。
        int npad = (nsizeimage / nheight) - nwidth * 3;
        int ndata[] = new int[nheight * nwidth];
        byte brgb[] = new byte[ (nwidth + npad) * 3 * nheight];
        fs.read(brgb, 0, (nwidth + npad) * 3 * nheight);
        int nindex = 0;
        for (int j = 0; j < nheight; j++)
        {
          for (int i = 0; i < nwidth; i++)
          {
            ndata[nwidth * (nheight - j - 1) + i] =
                (255 & 0xff) << 24
                | ( ( (int) brgb[nindex + 2] & 0xff) << 16)
                | ( ( (int) brgb[nindex + 1] & 0xff) << 8)
                | (int) brgb[nindex] & 0xff;
            /**   system.out.println("encoded color at ("
               +i + "," + j + ")is:" + nrgb + " (r,g,b)= ("
                   + ( (int) (brgb[2]) & 0xff) + ","
                   + ( (int) brgb[1] & 0xff) + ","
                   + ( (int) brgb[0] & 0xff) + ")");
             }*/
            nindex += 3;
          }
          nindex += npad;
        }
        image = toolkit.getdefaulttoolkit().createimage
            (new memoryimagesource(nwidth, nheight,
                                   ndata, 0, nwidth));
      }
      else if (nbitcount == 8)
      {
        // 必须确定颜色数。如果 clrsused 参数大于 0,
        // 则颜色数由它决定。如果它等于 0,则根据
        // bitsperpixel 计算颜色数。
        int nnumcolors = 0;
        if (nclrused > 0)
        {
          nnumcolors = nclrused;
        }
        else
        {
          nnumcolors = (1 & 0xff) << nbitcount;
        }
        system.out.println("the number of colors is" + nnumcolors);
        // 某些位图不计算 sizeimage 域,请找出
        // 这些情况并对它们进行修正。
        if (nsizeimage == 0)
        {
          nsizeimage = ( ( ( (nwidth * nbitcount) + 31) & ~31) >> 3);
          nsizeimage *= nheight;
          system.out.println("nsizeimage (backup) is" + nsizeimage);
        }
        // 读取调色板颜色。
        int npalette[] = new int[nnumcolors];
        byte bpalette[] = new byte[nnumcolors * 4];
        fs.read(bpalette, 0, nnumcolors * 4);
        int nindex8 = 0;
        for (int n = 0; n < nnumcolors; n++)
        {
          npalette[n] = (255 & 0xff) << 24
              | ( ( (int) bpalette[nindex8 + 2] & 0xff) << 16)
              | ( ( (int) bpalette[nindex8 + 1] & 0xff) << 8)
              | (int) bpalette[nindex8] & 0xff;
          /**system.out.println ("palette color "+n
                     +" is:" + npalette[n] + " (res,r,g,b)= ("
              + ( (int) (bpalette[nindex8 + 3]) & 0xff) + ","
              + ( (int) (bpalette[nindex8 + 2]) & 0xff) + ","
              + ( (int) bpalette[nindex8 + 1] & 0xff) + ","
              + ( (int) bpalette[nindex8] & 0xff) + ")");
           */
          nindex8 += 4;
        }
        // 读取图像数据(实际上是调色板的索引)
        // 扫描行仍被补足到 4 个字节。
        int npad8 = (nsizeimage / nheight) - nwidth;
        system.out.println("npad is:" + npad8);
        int ndata8[] = new int[nwidth * nheight];
        byte bdata[] = new byte[ (nwidth + npad8) * nheight];
        fs.read(bdata, 0, (nwidth + npad8) * nheight);
        nindex8 = 0;
        for (int j8 = 0; j8 < nheight; j8++)
        {
          for (int i8 = 0; i8 < nwidth; i8++)
          {
            ndata8[nwidth * (nheight - j8 - 1) + i8] =
                npalette[ ( (int) bdata[nindex8] & 0xff)];
            nindex8++;
          }
          nindex8 += npad8;
        }
        image = toolkit.getdefaulttoolkit().createimage
            (new memoryimagesource(nwidth, nheight,
                                   ndata8, 0, nwidth));
      }
      else
      {
        system.out.println("not a 24-bit or 8-bit windows bitmap, aborting...");
        image = (image)null;
      }
      fs.close();
      return image;
    }
    catch (exception e)
    {
      system.out.println("caught exception in loadbitmap!");
    }
    return (image)null;
  }
  public void waitforimage(image image)
  {
    //tracker = new mediatracker(this);
    try
    {
      tracker.addimage(image, 0); //public void addimage(image image,int id)
      //tracker.waitforall();
      tracker.waitforid(0);
      tracker.checkall(true);
      /** while(!tracker.checkid(0))
       {
         tracker.waitforid(0);
       }*/
      if (tracker.iserrorany())
      {
        // system.out.println(tracker.geterrorsany().tostring());
        system.out.println("加载图像出现错误!");
        system.exit(0);
      }
      // loadstatus = tracker.statusid( 0, false );
      // tracker.removeimage(image, 0);
    }
    catch (interruptedexception e)
    {
      e.printstacktrace();
    }
  } // waitforimage
  public void checkimage(image image)
  {
    waitforimage(image);
    int imagewidth = image.getwidth(null);
    if (imagewidth < 1)
    {
      throw new illegalargumentexception("image width " + imagewidth +
                                         " is out of range");
    }
    int imageheight = image.getheight(null);
    if (imageheight < 1)
    {
      throw new illegalargumentexception("image height " + imageheight +
                                         " is out of range");
    }
    // system.out.println( "image size=" + imagewidth + "x" + imageheight );
  } // checkimage
  public void encodejpeg(outputstream outputstream, image outputimage,
                         float outputquality) throws java.io.ioexception
  {
    int outputwidth = outputimage.getwidth(null);
    if (outputwidth < 1)
    {
      throw new illegalargumentexception("output image width " + outputwidth +
                                         " is out of range");
    }
    int outputheight = outputimage.getheight(null);
    if (outputheight < 1)
    {
      throw new illegalargumentexception("output image height " + outputheight +
                                         " is out of range");
    }
    // get a buffered image from the image.
    bufferedimage bi = new bufferedimage(outputwidth, outputheight,
                                         bufferedimage.type_int_rgb);
    graphics2d bicontext = bi.creategraphics();
    bicontext.drawimage(outputimage, 0, 0, null);
    // note that additional drawing such as watermarks or logos can be placed here.
    // com.sun.image.codec.jpeg package is included in sun and ibm sdk 1.3
    jpegimageencoder encoder = jpegcodec.createjpegencoder(outputstream);
    // the default quality is 0.75.
    jpegencodeparam jep = jpegcodec.getdefaultjpegencodeparam(bi);
    jep.setquality(outputquality, true);
    encoder.encode(bi, jep);
    // encoder.encode( bi );
    outputstream.flush();
  } // encodeimage
  /** adjusts the size of the image to the given coordinates.
   * if width or height is -1, the image aspect ration is maintained.
   * <p>
   * hints are one of scale_default, scale_fast, scale_smooth,
   * scale_replicate, scale_area_averaging as defined in java.awt.image.
   */
  public image setsize(image image, int width, int height, int hints)
  {
    return image.getscaledinstance(width, height, hints);
  } // setsize
  public image setsize(image image, int width, int height)
  {
    return setsize(image, width, height, java.awt.image.scale_default); //setsize调用的是上一个方法.
  } // setsize
  //component initialization
  public static void main(string[] args)
  {
    screenpicsaver sps = new screenpicsaver();
    // string sdir = new string("d://");
    // string sfile = new string("desktop.bmp");
    string outputfilename = new string("d://desktop.jpg");
    //image inputimage = toolkit.getdefaulttoolkit().getimage(inputfilename);
    //image inputimage = sps.loadbitmap(sdir, sfile);
    //===============================================================
    bufferedimage bufferedimage = null;
    robot robot;
    image inputimage = null;
    try
    {
      robot = new robot();
      bufferedimage = robot.createscreencapture(new rectangle(toolkit.
          getdefaulttoolkit().getscreensize())); //得到桌面图像的bufferedimage对象
    }
    catch (exception ex)
    {
      ex.printstacktrace();
    }
    int width = bufferedimage.getwidth();
    int height = bufferedimage.getheight();
    inputimage = bufferedimage.getscaledinstance(width, height,
                                                 bufferedimage.type_int_rgb); //将bufferedimage对象转化位image对象
    mediatracker tracker = new mediatracker(new component()
    {});
    int outputwidth = inputimage.getwidth(null); //使得新图像和原图像的宽度一样
    float outputquality = 0.80f;
    image outputimage = sps.setsize(inputimage, outputwidth, -1); //-1表示在宽度确定的情况下,高度在原图像的基础上成比例缩放
    try
    {
      tracker.addimage(inputimage, 0);
      //sps.tracker.waitforall();
      tracker.waitforid(0);
      tracker.checkall(true);
    }
    catch (interruptedexception e)
    {
      e.printstacktrace();
    }
    int imagewidth = inputimage.getwidth(null);
    if (imagewidth < 1)
    {
      throw new illegalargumentexception("image width " + imagewidth +
                                         " is out of range");
    }
    int imageheight = inputimage.getheight(null);
    if (imageheight < 1)
    {
      throw new illegalargumentexception("image height " + imageheight +
                                         " is out of range");
    }
    try
    {
      fileoutputstream fos = new fileoutputstream(outputfilename);
      sps.encodejpeg(fos, outputimage, outputquality);
      fos.flush();
      fos.close();
    }
    catch (exception e)
    {
      e.printstacktrace();
    }
    system.exit(0);
  }
}

扫描关注微信公众号