Java Code Examples for java.awt.image.BufferedImage#getHeight()

The following examples show how to use java.awt.image.BufferedImage#getHeight() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
private static BufferedImage resizeImage(BufferedImage originalImage) {
    int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
    float ratio = (float) originalImage.getWidth() / (float) originalImage.getHeight();
    int width = 80;
    int height = 25;
    if (ratio <= 1) {
        height = (int) ((float) width * ratio);
    } else {
        width = (int) ((float) height * (float) ratio);
    }
    BufferedImage resizedImage = new BufferedImage(width, height, type);
    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, width, height, null);
    g.dispose();

    return resizedImage;
}
 
Example 2
Source Project: hifive-pitalium   File: PtlItTestBase.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected boolean matchesSafely(BufferedImage image, Description description) {
	int width = this.image.getWidth();
	int height = this.image.getHeight();
	if (image.getWidth() != width) {
		description.appendText("image width mismatch.");
		return false;
	}
	if (image.getHeight() != height) {
		description.appendText("image height mismatch.");
		return false;
	}

	int[] expect = ImageUtils.getRGB(this.image, width, height);
	int[] actual = ImageUtils.getRGB(image, width, height);
	for (int i = 0; i < expect.length; i++) {
		if (expect[i] != actual[i]) {
			description.appendText("pixel mismatch.");
			return false;
		}
	}

	return true;
}
 
Example 3
private static void compare(BufferedImage a, BufferedImage b) {
    int w = a.getWidth();
    int h = a.getHeight();

    if (w != b.getWidth() || h != b.getHeight()) {
        throw new RuntimeException("Test FAILED!");
    }

    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            if (a.getRGB(x, y) != b.getRGB(x, y)) {
                throw new RuntimeException("Test FAILED!");
            }
        }
    }
}
 
Example 4
public bug6937798() {
    final JTable table = createCountryTable();
    table.setShowGrid(true);
    table.setSize(100, 100);

    BufferedImage im = new BufferedImage(table.getWidth(), table.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics g = im.getGraphics();
    table.print(g);
    g.dispose();

    for (int i = 0; i < im.getHeight(); i++) {
        for (int j = 0; j < im.getWidth(); j++) {
            if (im.getRGB(i, j) == table.getGridColor().getRGB()) {
                System.out.println("got it!");
                return;
            }
        }
    }
    throw new RuntimeException("no table's grid detected....");
}
 
Example 5
/**
 * 搜索人脸
 *
 * @param image 人脸照片
 * @return
 * @throws IOException
 */
public static Result search(BufferedImage image) {
    if (image == null) {
        return null;
    }
    SeetaImageData imageData = new SeetaImageData(image.getWidth(), image.getHeight(), 3);
    imageData.data = ImageUtils.getMatrixBGR(image);
    RecognizeResult rr = seeta.recognize(imageData);

    if (rr == null || rr.index == -1) {
        return null;
    }
    Result result = new Result(rr);
    result.setKey(FaceDao.findKeyByIndex(rr.index));
    return result;
}
 
Example 6
Source Project: birt   File: SVGGraphics2D.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected Element createTexturePaint( TexturePaint paint, String imgId,
		boolean highlight )
{
	Element elem = dom.createElement( "pattern" ); //$NON-NLS-1$
	if ( highlight )
		elem.setAttribute( "id", getTextureId( paint ) + "h" ); //$NON-NLS-1$ //$NON-NLS-2$
	else
		elem.setAttribute( "id", getTextureId( paint ) ); //$NON-NLS-1$
	
	BufferedImage img = paint.getImage( );
	int width = img.getWidth( );
	int height = img.getHeight( );
	elem.setAttribute( "patternUnits", "userSpaceOnUse" );  //$NON-NLS-1$//$NON-NLS-2$
	elem.setAttribute( "width", Integer.toString( width ) ); //$NON-NLS-1$
	elem.setAttribute( "height", Integer.toString( height ) ); //$NON-NLS-1$

	Element elemUse = dom.createElement( "use" ); //$NON-NLS-1$
	elemUse.setAttribute( "x", "0" );  //$NON-NLS-1$//$NON-NLS-2$
	elemUse.setAttribute( "y", "0" );  //$NON-NLS-1$//$NON-NLS-2$
	elemUse.setAttribute( "xlink:href", "#" + imgId );  //$NON-NLS-1$//$NON-NLS-2$
	
	elem.appendChild( elemUse );
	return elem;
}
 
Example 7
Source Project: MSPaintIDE   File: TextEditorManager.java    License: MIT License 5 votes vote down vote up
private File createImageFile() throws IOException, ExecutionException, InterruptedException {
    File tempImage = new File(MainGUI.APP_DATA, "opened\\" + this.originalFile.getName() + ".png");
    tempImage.mkdirs();

    String text = new String(Files.readAllBytes(this.originalFile.toPath()));
    LOGGER.info("text = " + text);

    int padding = SettingsManager.getInstance().getSetting(Setting.EDIT_FILE_SIZE);

    BufferedImage image = new BufferedImage(600, 500, BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x < image.getWidth(); x++) {
        for (int y = 0; y < image.getHeight(); y++) {
            image.setRGB(x, y, Color.WHITE.getRGB());
        }
    }

    ImageIO.write(image, "png", tempImage);

    ScannedImage letterGrid = generateLetterGrid(startupLogic, originalFile, text);
    int[] coords = getBiggestCoordinates(letterGrid);
    applyPadding(letterGrid, padding, padding);

    BufferedImage bufferedImage = new BufferedImage(coords[0] + padding * 2, coords[1] + padding * 2, BufferedImage.TYPE_INT_ARGB);

    LetterFileWriter letterFileWriter = new LetterFileWriter(letterGrid, bufferedImage, tempImage);
    letterFileWriter.writeToFile();

    return tempImage;
}
 
Example 8
private void checkUniqueColors(final BufferedImage src, final Palette palette) throws ImageWriteException {
    final BufferedImage dst = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_RGB);
    dst.getGraphics().drawImage(src, 0, 0, src.getWidth(), src.getHeight(), null);
    Dithering.applyFloydSteinbergDithering(dst, palette);
    final Palette ditheredPalette = new PaletteFactory().makeExactRgbPaletteSimple(dst, palette.length() * 2);
    assertEquals(palette.length(), ditheredPalette.length());
}
 
Example 9
Source Project: MyBox   File: ImageGray.java    License: Apache License 2.0 5 votes vote down vote up
public static BufferedImage byteGray(BufferedImage image) {
    try {
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage grayImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D graphics = grayImage.createGraphics();
        graphics.drawImage(image, 0, 0, null);
        return grayImage;
    } catch (Exception e) {
        logger.error(e.toString());
        return image;
    }
}
 
Example 10
Source Project: neodymium-library   File: ImageHelper.java    License: MIT License 5 votes vote down vote up
/**
 * Scales a binary image up to the given size. Does not innately preserve Width/ Height ratio. Used in closeImage.
 * Divides the bigger image into blocks. Sets all the pixels in the block to the foreground color if the
 * corresponding pixel has the foreground color. If there are some pixels leftover, the last blocks gets them, no
 * matter how many there are.
 * 
 * @param img
 *            The original image
 * @param newWidth
 *            The width of the new image after scaling
 * @param newHeight
 *            The height of the new image after scaling
 * @param scalingFactor
 *            The scaling factor for the image size
 * @param rgbForegroundColor
 *            The foreground color
 * @return A upscaled BufferedImage copy of the original image
 */
protected static BufferedImage scaleUpMaskImage(final BufferedImage img, final int newWidth, final int newHeight,
                                                final int scalingFactor, final int rgbForegroundColor)
{

    final BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);

    // Go through every pixel of the image to scale
    for (int w = 0; w < img.getWidth(); w++)
    {
        for (int h = 0; h < img.getHeight(); h++)
        {
            // Check if it has the foreground color
            if (img.getRGB(w, h) == rgbForegroundColor)
            {
                // And set every pixel in the corresponding block true if it
                // does
                for (int x = w * scalingFactor; x < w * scalingFactor + scalingFactor; x++)
                {
                    for (int y = h * scalingFactor; y < h * scalingFactor + scalingFactor; y++)
                    {
                        // So long as it doesn't go over the border
                        if (x < scaledImage.getWidth() && y < scaledImage.getHeight())
                        {
                            scaledImage.setRGB(x, y, rgbForegroundColor);
                        }
                    }
                }
            }
        }
    }

    return scaledImage;
}
 
Example 11
public Tensor<Float> convertBufferedImageToTensor(BufferedImage image) {
        //if (image.getWidth()!=DESIRED_SIZE || image.getHeight()!=DESIRED_SIZE)
        {
            // also make it an RGB image
            image = resize(image,DESIRED_SIZE, DESIRED_SIZE);
           // image = resize(image,image.getWidth(), image.getHeight());
        }
        int width = image.getWidth();
        int height = image.getHeight();
        Raster r = image.getRaster();
        int[] rgb = new int[3];
        //int[] data = new int[width * height];
        //image.getRGB(0, 0, width, height, data, 0, width);
        float[][][][] rgbArray = new float[1][height][width][3];
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                //Color color = new Color(data[i * width + j]);
//                rgbArray[0][i][j][0] = color.getRed() - MEAN_PIXEL[0];
//                rgbArray[0][i][j][1] = color.getGreen() - MEAN_PIXEL[1];
//                rgbArray[0][i][j][2] = color.getBlue() - MEAN_PIXEL[2];
                rgb = r.getPixel(j,i,rgb);
                rgbArray[0][i][j][0] = rgb[0] - MEAN_PIXEL[0];
                rgbArray[0][i][j][1] = rgb[1] - MEAN_PIXEL[1];
                rgbArray[0][i][j][2] = rgb[2] - MEAN_PIXEL[2];
            }
        }
        return Tensor.create(rgbArray, Float.class);
    }
 
Example 12
Source Project: gameserver   File: BattleHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * convert image to data  map_00.png --> map_00.dat 仅保留alpha值
 * @param args
 * @throws Throwable
 */
public static final void main(String[] args) throws Throwable {
  String basepath = "/Users/jsding/Documents/workspace/newenginegames/snsgames/babywar/server/data/map";
  for (int mapId : allmapIds) {
    
    String filename = null;
    if (mapId < 10) {
      filename = "map_0"+mapId;
    } else {
      filename = "map_"+mapId;
    }
    BufferedImage image = ImageIO.read(new File(basepath, filename + ".png"));
    int width = image.getWidth();
    int height = image.getHeight();
    
    DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(basepath, filename + ".dat")));
    dos.writeInt(width);
    dos.writeInt(height);
    for (int j = 0; j< height; j++) {
      for (int i = 0; i < width; i++) {
        int color = image.getRGB(i, j);
        dos.writeByte((color >> 24) & 0xff);
      }
    }
    
    dos.flush();
    dos.close();
    
  }

}
 
Example 13
public OffScreenImageSource(BufferedImage image,
                            Hashtable properties) {
    this.image = image;
    if (properties != null) {
        this.properties = properties;
    } else {
        this.properties = new Hashtable();
    }
    width  = image.getWidth();
    height = image.getHeight();
}
 
Example 14
@SuppressWarnings("SameParameterValue")
public static void checkImage(BufferedImage image, String path, String gfName) throws Exception {

    String[] testDataVariant = {
            "osx_hardware_rendering", "osx_software_rendering",
            "osx_sierra_rendering", "osx_lowres_rendering",
            "linux_rendering", "windows_rendering", "windows7_rendering"};

    String testDataStr = System.getProperty("testdata");
    assertNotNull("testdata property is not set", testDataStr);

    File testData = new File(testDataStr, "quality" + File.separator + path);
    assertTrue("Test data dir does not exist", testData.exists());

    if (System.getProperty("gentestdata") == null) {
        boolean failed = true;
        StringBuilder failureReason = new StringBuilder();
        for (String variant : testDataVariant) {
            File goldenFile = new File(testData, variant + File.separator +
                    gfName);
            if (!goldenFile.exists()) continue;

            BufferedImage goldenImage = ImageIO.read(goldenFile);
            assertNotNull("no registered ImageReader claims to be able to read the stream: "
                    + goldenFile, goldenImage);
            failed = true;
            if (image.getWidth() != goldenImage.getWidth() ||
                    image.getHeight() != image.getHeight()) {
                failureReason.append(variant).append(" : Golden image and result have different sizes\n");
                continue;
            }

            Raster gRaster = goldenImage.getData();
            Raster rRaster = image.getData();
            int[] gArr = new int[3];
            int[] rArr = new int[3];
            failed = false;
            scan:
            for (int i = 0; i < gRaster.getWidth(); i++) {
                for (int j = 0; j < gRaster.getHeight(); j++) {
                    gRaster.getPixel(i, j, gArr);
                    rRaster.getPixel(i, j, rArr);
                    assertTrue(gArr.length == rArr.length);
                    for (int k = 0; k < gArr.length; k++) {
                        if (gArr[k] != rArr[k]) {
                            failureReason.append(variant).append(" : Different pixels found ").
                                    append("at (").append(i).append(",").append(j).append(")");
                            failed = true;
                            break scan;
                        }
                    }
                }
            }

            if (!failed) break;
        }

        if (failed) throw new RuntimeException(failureReason.toString());
    } else {
        ImageIO.write(image, "png", new File(testData, gfName));
    }
}
 
Example 15
Source Project: Spark   File: AvatarPanel.java    License: Apache License 2.0 4 votes vote down vote up
private void changeAvatar(final File selectedFile, final Component parent) {
     SwingWorker worker = new SwingWorker() {
         @Override
public Object construct() {
             return resizeImage(selectedFile);
         }

         @Override
public void finished() {
             BufferedImage avatarImage = (BufferedImage)get();
             String message = "";
             int finalImageWidth = avatarImage.getWidth();
             int finalImageHeight = avatarImage.getHeight();
             boolean showWarning = false;
             if (finalImageWidth != finalImageHeight) {
                 message += "\u2022 " + Res.getString("message.image.not.square") + "\n";
                 showWarning = true;
             }
             if (finalImageWidth < 32 && finalImageHeight < 32) {
                 message += "\u2022 " + Res.getString("message.image.small.resolution") + "\n";
                 showWarning = true;
             }
             if (showWarning) {
                 message += Res.getString("message.image.suggestion");
                 JOptionPane.showMessageDialog(parent, message, Res.getString("title.warning"), JOptionPane.WARNING_MESSAGE);
             }
             /*
             // Check size.
             long length = GraphicUtils.getBytesFromImage(avatarImage).length * 8;

             long k = 8192;

             long actualSize = (length / k) + 1;

             if (actualSize > 16) {
                 // Do not allow
                 JOptionPane.showMessageDialog(parent, Res.getString("message.image.too.large"));
                 return;
             }
             */
             //convert BufferedImage to bytes
             try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                 ImageIO.write(avatarImage, "png", baos);
                 setAvatar(new ImageIcon(avatarImage));
                 setAvatarBytes(baos.toByteArray());
             } catch (IOException ex) {
                 Log.error(ex);
             }
         }
     };

     worker.start();
 }
 
Example 16
private void test(String h, String q_s, int u, TIntArrayList query) throws IOException, InterruptedException {
    // Read original image
    BufferedImage img = ImageIO.read(new File(h + "test.png"));
    int width = img.getWidth();
    int height = img.getHeight();

    ImageIO.write(resizeImage(img, 600, 600), "png",
            new File(h + "res/original.png"));

    int s = width * height;

    boolean[] mtx = new boolean[s];
    int i = 0;

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            int rgb = grey(img, x, y);

            mtx[i++] = rgb > 250;
        }
    }

    // Write to stdout
    /*
     i = 0;
     for (int y = 0; y < height; y++) {
     for (int x = 0; x < width; x++)
     pf("%d ", (mtx[i++] ? 1 : 0));
     p("\n");
     } */

    BufferedImage img2 = writeQuery(h, width, height, mtx, query);

    // Write evidence
    PrintWriter w = new PrintWriter(h + "evid", "UTF-8");

    // wf(w, "/* Evidence */ \n");
    wf(w, "%d ", s - query.size());
    for (int j = 0; j < s; j++) {
        if (query.contains(j)) {
            continue;
        }
        wf(w, "%d %d ", j, mtx[j] ? 1 : 0);
    }
    w.close();

    // Execute MPE
    String r = "./daoopt -f 1.uai -e evid";
    Process proc = Runtime.getRuntime().exec(r, new String[0], new File(h));
    ArrayList<String> out = exec(proc);
    String res = out.get(out.size() - 1);
    String[] aux = res.split(" ");

    BufferedImage img3 = writeRecovered(h, width, height, aux);

    BufferedImage join = joinBufferedImage(img, img2, img3);
    BufferedImage result = resizeImage(join, 1200, 400);

    ImageIO.write(result, "png",
            new File(f("%s/res/%s-result%d.png", h, q_s, u)));
}
 
Example 17
/**
 * Remove white borders from a gray-scale image.
 * @param source
 * @return the cropped image.
 */
public static BufferedImage cropWhiteBorder(BufferedImage source) {
    int upperBound = -1, lowerBound = -1, leftBound = -1, rightBound = -1;

    //Check upper bound
    upper: for(int y = 0; y < source.getHeight(); y++) {
        for(int x = 0; x < source.getWidth(); x++) {
            if(source.getRGB(x, y) != Color.white.getRGB()) {
                upperBound = y;
                break upper;
            }
        }
    }

    //Check lower bound
    lower: for(int y = source.getHeight() - 1; y >= 0; y--) {
        for(int x = 0; x < source.getWidth(); x++) {
            if(source.getRGB(x, y) != Color.white.getRGB()) {
                lowerBound = y;
                break lower;
            }
        }
    }

    //Check left bound
    left: for(int x = 0; x < source.getWidth(); x++) {
        for(int y = 0; y < source.getHeight(); y++) {
            if(source.getRGB(x, y) != Color.white.getRGB()) {
                leftBound = x;
                break left;
            }
        }
    }

    //Check right bound
    right: for(int x = source.getWidth() - 1; x >= 0; x--) {
        for(int y = 0; y < source.getHeight(); y++) {
            if(source.getRGB(x, y) != Color.white.getRGB()) {
                rightBound = x;
                break right;
            }
        }
    }

    //Crop desired area from source image
    return source.getSubimage(leftBound, upperBound, rightBound - leftBound + 1, lowerBound - upperBound + 1);
}
 
Example 18
/**
 * <p>Returns a thumbnail of a source image.</p>
 * <p>This method offers a good trade-off between speed and quality.
 * The result looks better than
 * {@link #createThumbnailFast(java.awt.image.BufferedImage, int)} when
 * the new size is less than half the longest dimension of the source
 * image, yet the rendering speed is almost similar.</p>
 *
 * @see #createThumbnailFast(java.awt.image.BufferedImage, int)
 * @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
 * @see #createThumbnail(java.awt.image.BufferedImage, int)
 * @param image the source image
 * @param newWidth the width of the thumbnail
 * @param newHeight the height of the thumbnail
 * @return a new compatible <code>BufferedImage</code> containing a
 *   thumbnail of <code>image</code>
 * @throws IllegalArgumentException if <code>newWidth</code> is larger than
 *   the width of <code>image</code> or if code>newHeight</code> is larger
 *   than the height of <code>image or if one the dimensions is not &gt; 0</code>
 */
public static BufferedImage createThumbnail(BufferedImage image,
                                            int newWidth, int newHeight) {
    int width = image.getWidth();
    int height = image.getHeight();

    if (newWidth >= width || newHeight >= height) {
        throw new IllegalArgumentException("newWidth and newHeight cannot" +
                                           " be greater than the image" +
                                           " dimensions");
    } else if (newWidth <= 0 || newHeight <= 0) {
        throw new IllegalArgumentException("newWidth and newHeight must" +
                                           " be greater than 0");
    }

    BufferedImage thumb = image;

    do {
        if (width > newWidth) {
            width /= 2;
            if (width < newWidth) {
                width = newWidth;
            }
        }

        if (height > newHeight) {
            height /= 2;
            if (height < newHeight) {
                height = newHeight;
            }
        }

        BufferedImage temp = createCompatibleImage(image, width, height);
        Graphics2D g2 = temp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(thumb, 0, 0, temp.getWidth(), temp.getHeight(), null);
        g2.dispose();

        thumb = temp;
    } while (width != newWidth || height != newHeight);

    return thumb;
}
 
Example 19
/**
 * <p>Returns a thumbnail of a source image.</p>
 * <p>This method offers a good trade-off between speed and quality.
 * The result looks better than
 * {@link #createThumbnailFast(java.awt.image.BufferedImage, int)} when
 * the new size is less than half the longest dimension of the source
 * image, yet the rendering speed is almost similar.</p>
 *
 * @see #createThumbnailFast(java.awt.image.BufferedImage, int)
 * @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
 * @see #createThumbnail(java.awt.image.BufferedImage, int)
 * @param image the source image
 * @param newWidth the width of the thumbnail
 * @param newHeight the height of the thumbnail
 * @return a new compatible <code>BufferedImage</code> containing a
 *   thumbnail of <code>image</code>
 * @throws IllegalArgumentException if <code>newWidth</code> is larger than
 *   the width of <code>image</code> or if code>newHeight</code> is larger
 *   than the height of <code>image or if one the dimensions is not &gt; 0</code>
 */
public static BufferedImage createThumbnail(BufferedImage image,
                                            int newWidth, int newHeight) {
    int width = image.getWidth();
    int height = image.getHeight();

    if (newWidth >= width || newHeight >= height) {
        throw new IllegalArgumentException("newWidth and newHeight cannot" +
                                           " be greater than the image" +
                                           " dimensions");
    } else if (newWidth <= 0 || newHeight <= 0) {
        throw new IllegalArgumentException("newWidth and newHeight must" +
                                           " be greater than 0");
    }

    BufferedImage thumb = image;

    do {
        if (width > newWidth) {
            width /= 2;
            if (width < newWidth) {
                width = newWidth;
            }
        }

        if (height > newHeight) {
            height /= 2;
            if (height < newHeight) {
                height = newHeight;
            }
        }

        BufferedImage temp = createCompatibleImage(image, width, height);
        Graphics2D g2 = temp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(thumb, 0, 0, temp.getWidth(), temp.getHeight(), null);
        g2.dispose();

        thumb = temp;
    } while (width != newWidth || height != newHeight);

    return thumb;
}
 
Example 20
Source Project: consulo   File: TipUIUtil.java    License: Apache License 2.0 4 votes vote down vote up
private static void updateImages(StringBuilder text, ClassLoader tipLoader, JEditorPane browser) {
  final boolean dark = StyleManager.get().getCurrentStyle().isDark();

  IdeFrame af = IdeFrameUtil.findActiveRootIdeFrame();
  Component comp = af != null ? TargetAWT.to(af.getWindow()) : browser;
  int index = text.indexOf("<img", 0);
  while (index != -1) {
    final int end = text.indexOf(">", index + 1);
    if (end == -1) return;
    final String img = text.substring(index, end + 1).replace('\r', ' ').replace('\n', ' ');
    final int srcIndex = img.indexOf("src=");
    final int endIndex = img.indexOf(".png", srcIndex);
    if (endIndex != -1) {
      String path = img.substring(srcIndex + 5, endIndex);
      if (!path.endsWith("_dark") && !path.endsWith("@2x")) {
        boolean hidpi = JBUI.isPixHiDPI(comp);
        path += (hidpi ? "@2x" : "") + (dark ? "_dark" : "") + ".png";
        URL url = ResourceUtil.getResource(tipLoader, "/tips/", path);
        if (url != null) {
          String newImgTag = "<img src=\"" + path + "\" ";
          try {
            BufferedImage image = ImageIO.read(url.openStream());
            int w = image.getWidth();
            int h = image.getHeight();
            if (UIUtil.isJreHiDPI(comp)) {
              // compensate JRE scale
              float sysScale = JBUI.sysScale(comp);
              w = (int)(w / sysScale);
              h = (int)(h / sysScale);
            }
            else {
              // compensate image scale
              float imgScale = hidpi ? 2f : 1f;
              w = (int)(w / imgScale);
              h = (int)(h / imgScale);
            }
            // fit the user scale
            w = (int)(JBUI.scale((float)w));
            h = (int)(JBUI.scale((float)h));

            newImgTag += "width=\"" + w + "\" height=\"" + h + "\"";
          }
          catch (Exception ignore) {
            newImgTag += "width=\"400\" height=\"200\"";
          }
          newImgTag += "/>";
          text.replace(index, end + 1, newImgTag);
        }
      }
    }
    index = text.indexOf("<img", index + 1);
  }
}