/** * Run method, for loading image in separate thread * * @see java.lang.Runnable#run() */ public void run() { if (_inPanel) { // use either exif thumbnail or photo scaled down to sensible size if (_photo.getExifThumbnail() != null) { // Use exif thumbnail Image image = new ImageIcon(_photo.getExifThumbnail()).getImage(); _thumbnail = ImageUtils.createScaledImage(image, image.getWidth(null), image.getHeight(null)); image = null; } else { // no exif thumbnail available, going to have to read whole thing int picWidth = _photo.getWidth(); int picHeight = _photo.getHeight(); if (picWidth > -1 && picHeight > -1) { // Just set a "reasonable" thumbnail size for now final int DEFAULT_THUMB_SIZE = 400; // calculate maximum thumbnail size Dimension thumbSize = ImageUtils.getThumbnailSize( picWidth, picHeight, DEFAULT_THUMB_SIZE, DEFAULT_THUMB_SIZE); // Make icon to load image into Image image = _photo.createImageIcon().getImage(); // save scaled, smoothed thumbnail for reuse _thumbnail = ImageUtils.createScaledImage(image, thumbSize.width, thumbSize.height); image = null; } else _loadFailed = true; } } else { _thumbnail = _photo.createImageIcon().getImage(); } _loadingImage = false; repaint(); }
private static void rotate( BufferedImage srcImg, BufferedImage leftImg, BufferedImage rightImg, List<BufferedImage> outImages, int maxAmount) { for (int i = ANGLE_DEVIATION_STEP; i < MAX_ANGLE_DEVIATION; i = i + ANGLE_DEVIATION_STEP) { // outImages.add( // compose( // rotate(leftImg, i*Math.PI/180), // rightImg, // ImageUtils.deepCopy(srcImg))); // outImages.add( // compose( // rotate(leftImg, -i*Math.PI/180), // rightImg, // ImageUtils.deepCopy(srcImg))); // // // outImages.add( // compose( // leftImg, // rotate(rightImg, i*Math.PI/180), // ImageUtils.deepCopy(srcImg))); // outImages.add( // compose( // leftImg, // rotate(rightImg, -i*Math.PI/180), // ImageUtils.deepCopy(srcImg))); if (maxAmount > outImages.size()) outImages.add( compose( rotate(leftImg, i * Math.PI / 180), rotate(rightImg, i * Math.PI / 180), ImageUtils.deepCopy(srcImg))); if (maxAmount > outImages.size()) outImages.add( compose( rotate(leftImg, -i * Math.PI / 180), rotate(rightImg, -i * Math.PI / 180), ImageUtils.deepCopy(srcImg))); // outImages.add( // compose( // rotate(leftImg, -i*Math.PI/180), // rotate(rightImg, i*Math.PI/180), // ImageUtils.deepCopy(srcImg))); // outImages.add( // compose( // rotate(leftImg, i*Math.PI/180), // rotate(rightImg, -i*Math.PI/180), // ImageUtils.deepCopy(srcImg))); } // for (int i = 0; i < MAX_ANGLE_DEVIATION; i++) return; }
private void edges() { int[] greypxls = imageUtils.convertToGrey(img); int[] edgepxls = imageUtils.edges(greypxls, img.getWidth(), img.getHeight()); BufferedImage greyimg = imageUtils.intToImage(greypxls, img.getWidth(), img.getHeight()); picLabel.setIcon(new ImageIcon(greyimg)); panel.repaint(); BufferedImage edgeimg = imageUtils.intToImage(edgepxls, img.getWidth(), img.getHeight()); picLabel1.setIcon(new ImageIcon(edgeimg)); panel_1.repaint(); }
public void handleIntent(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CAPTURE) { setCapturedImage(); } else if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_GALLERY && null != data) { mImagePair.imagePath = ImageUtils.getSmallImageFromSDCard( folderName, ImageUtils.getRealPathFromURI(mContext, data.getData()), mWidth, mHeight); mImagePair.imageView.setImageBitmap( ImageUtils.getBitmapFromFile(mImagePair.imagePath, mWidth, mHeight)); } else if (resultCode == Activity.RESULT_CANCELED && (requestCode == REQUEST_CAPTURE || requestCode == REQUEST_GALLERY)) { mImagePair.imagePath = null; } }
public Drawable getDrawable(String source) { File output = null; if (destroyed) { return loading.getDrawable(source); } try { output = File.createTempFile("image", ".jpg", dir); InputStream is = fetch(source); if (is != null) { boolean success = FileUtils.save(output, is); if (success) { Bitmap bitmap = ImageUtils.getBitmap(output, width, Integer.MAX_VALUE); if (bitmap == null) { return loading.getDrawable(source); } loadedBitmaps.add(new WeakReference<Bitmap>(bitmap)); BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; } else { return loading.getDrawable(source); } } else { return loading.getDrawable(source); } } catch (IOException e) { return loading.getDrawable(source); } finally { if (output != null) output.delete(); } }
/** * Create a new rendering session and test that rendering /layout/activity.xml on nexus 5 doesn't * throw any exceptions. */ @Test public void testRendering() throws ClassNotFoundException { // Create the layout pull parser. LayoutPullParser parser = new LayoutPullParser(APP_TEST_RES + "/layout/activity.xml"); // Create LayoutLibCallback. LayoutLibTestCallback layoutLibCallback = new LayoutLibTestCallback(getLogger()); layoutLibCallback.initResources(); // TODO: Set up action bar handler properly to test menu rendering. // Create session params. SessionParams params = getSessionParams(parser, ConfigGenerator.NEXUS_5, layoutLibCallback); RenderSession session = mBridge.createSession(params); if (!session.getResult().isSuccess()) { getLogger().error(session.getResult().getException(), session.getResult().getErrorMessage()); } // Render the session with a timeout of 50s. Result renderResult = session.render(50000); if (!renderResult.isSuccess()) { getLogger().error(session.getResult().getException(), session.getResult().getErrorMessage()); } try { String goldenImagePath = APP_TEST_DIR + "/golden/activity.png"; ImageUtils.requireSimilar(goldenImagePath, session.getImage()); } catch (IOException e) { getLogger().error(e, e.getMessage()); } }
public static BufferedImage convertImageToRGB( CLParams clParams, float[] sphericalImageFloats, int width, int height, ConversionType inputType) { FloatBuffer fb = Buffers.newDirectFloatBuffer(sphericalImageFloats); CLBuffer<FloatBuffer> sphericalImageBuffer = clParams.getContext().createBuffer(fb, CLBuffer.Mem.READ_WRITE); out.println("Transforming image to rgb coords"); CLKernel kernel = clParams.getKernel("convert_" + typeToString(inputType) + "_to_rgb"); kernel.putArg(sphericalImageBuffer).putArg(width).putArg(height).rewind(); long time = nanoTime(); clParams.getQueue().putWriteBuffer(sphericalImageBuffer, false); clParams.getQueue().put2DRangeKernel(kernel, 0, 0, width, height, 0, 0); clParams.getQueue().putReadBuffer(sphericalImageBuffer, true); time = nanoTime() - time; out.println("computation took: " + (time / 1000000) + "ms"); BufferedImage rgbImage = ImageUtils.createImage(width, height, sphericalImageBuffer, BufferedImage.TYPE_INT_RGB); return rgbImage; }
public static void saveImageResultsToPng(String prefix, ImageSearchHits hits, String queryImage) throws IOException { LinkedList<BufferedImage> results = new LinkedList<BufferedImage>(); int width = 0; for (int i = 0; i < hits.length(); i++) { // hits.score(i) // hits.doc(i).get("descriptorImageIdentifier") BufferedImage tmp = ImageIO.read(new FileInputStream(hits.doc(i).get("descriptorImageIdentifier"))); // if (tmp.getHeight() > 200) { double factor = 200d / ((double) tmp.getHeight()); tmp = ImageUtils.scaleImage(tmp, (int) (tmp.getWidth() * factor), 200); // } width += tmp.getWidth() + 5; results.add(tmp); } BufferedImage result = new BufferedImage(width, 220, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) result.getGraphics(); g2.setColor(Color.white); g2.setBackground(Color.white); g2.clearRect(0, 0, result.getWidth(), result.getHeight()); g2.setColor(Color.black); g2.setFont(Font.decode("\"Arial\", Font.BOLD, 12")); int offset = 0; int count = 0; for (Iterator<BufferedImage> iterator = results.iterator(); iterator.hasNext(); ) { BufferedImage next = iterator.next(); g2.drawImage(next, offset, 20, null); g2.drawString(hits.score(count) + "", offset + 5, 12); offset += next.getWidth() + 5; count++; } ImageIO.write( result, "PNG", new File(prefix + "_" + (System.currentTimeMillis() / 1000) + ".png")); }
/** * Adds resources for contact. * * @param tip the tool tip * @param protocolContact the protocol contact, which resources we're looking for */ private void addContactResourceTooltipLines(ExtendedTooltip tip, Contact protocolContact) { Collection<ContactResource> contactResources = protocolContact.getResources(); if (contactResources == null) return; Iterator<ContactResource> resourcesIter = contactResources.iterator(); while (resourcesIter.hasNext()) { ContactResource contactResource = resourcesIter.next(); // We only add the status icon if we have more than one resources, // otherwise it will always be identical to the contact status icon. ImageIcon protocolStatusIcon = null; if (contactResources.size() > 1) { protocolStatusIcon = ImageLoader.getIndexedProtocolIcon( ImageUtils.getBytesInImage(contactResource.getPresenceStatus().getStatusIcon()), protocolContact.getProtocolProvider()); } String resourceName = (contactResource.getPriority() >= 0) ? contactResource.getResourceName() + " (" + contactResource.getPriority() + ")" : contactResource.getResourceName(); if (protocolStatusIcon == null) tip.addSubLine(protocolStatusIcon, resourceName, 27); else tip.addSubLine(protocolStatusIcon, resourceName, 20); } tip.revalidate(); tip.repaint(); }
@Override public void process(Photo src, Photo dst) { float radius = Math.max(MIN_RADIUS, RADIUS_RATIO * Math.min(src.width(), src.height())); PointF[] a = new PointF[redeyePositions.size()]; ImageUtils.nativeRedEye( src.bitmap(), dst.bitmap(), redeyePositions.toArray(a), radius, DEFAULT_RED_INTENSITY); }
private void recordCtr() { int[] greypxls = imageUtils.convertToGrey(img); ctrMatrix = imageUtils.convertToMatrix(greypxls, img.getWidth(), img.getHeight()); BufferedImage gi = imageUtils.intToImage(greypxls, img.getWidth(), img.getHeight()); // put red dot in ctr int red = (255 << 16) + (0 << 8) + 0; int x = img.getWidth() / 2 + imageUtils.matrixres / 2; int y = img.getHeight() / 2 + imageUtils.matrixres / 2; gi.setRGB(x, y, red); gi.setRGB(x - 1, y, red); gi.setRGB(x + 1, y, red); gi.setRGB(x, y - 1, red); gi.setRGB(x, y + 1, red); picLabel.setIcon(new ImageIcon(gi)); panel.repaint(); }
private void doInit() { GUIUtils.setAppIcon(this, "burn.png"); GUIUtils.centerOnScreen(this); setVisible(true); int W = 28, H = W; boolean blur = false; float alpha = .7f; try { btnGetMap.setIcon(ImageUtils.loadScaledBufferedIcon("ok1.png", W, H, blur, alpha)); btnQuit.setIcon(ImageUtils.loadScaledBufferedIcon("charging.png", W, H, blur, alpha)); } catch (Exception e) { System.out.println(e); } _setupTask(); }
@Override public void run() { File file = new File(path); if (!file.exists()) { // 验证文件是否存在 return; } ImageUtils.scale2(path, type, path, 567, 390, false); // 测试OK commonUtil.p("图片转换结束"); }
private void findCtr() { int[] greypxls = imageUtils.convertToGrey(img); int[][] matrix = imageUtils.convertToMatrix(greypxls, img.getWidth(), img.getHeight()); int[] ctr = imageUtils.findCenter(matrix, ctrMatrix, img.getWidth(), img.getHeight()); BufferedImage imgwithctr = imageUtils.intToImage(greypxls, img.getWidth(), img.getHeight()); // put red dot at returned point if (ctr[0] > 0 && ctr[0] < img.getWidth() && ctr[1] > 0 && ctr[1] < img.getHeight()) { int red = (255 << 16) + (0 << 8) + 0; imgwithctr.setRGB(ctr[0], ctr[1], red); imgwithctr.setRGB(ctr[0] - 1, ctr[1], red); imgwithctr.setRGB(ctr[0] + 1, ctr[1], red); imgwithctr.setRGB(ctr[0], ctr[1] - 1, red); imgwithctr.setRGB(ctr[0], ctr[1] + 1, red); } picLabel1.setIcon(new ImageIcon(imgwithctr)); panel_1.repaint(); }
public DrawableObject(EnvObject envObject) { super(); this.setEnvObject(envObject); // Cached of all images needed for (Representation rp : envObject.getRepresentations()) { if (rp.getIcon() != null) { ImageUtils.queueImage(OBJECT_PATH + rp.getIcon()); } } // eop = new EnvObjectProperties(envObject); }
/** * Returns the avatar image corresponding to the source contact. In the case of multi user chat * contact returns null. * * @return the avatar image corresponding to the source contact. In the case of multi user chat * contact returns null */ public ImageIcon getAvatar() { byte[] avatarBytes = getAvatarBytes(); if (this.avatarBytes != avatarBytes) { this.avatarBytes = avatarBytes; this.avatar = null; } if ((this.avatar == null) && (this.avatarBytes != null) && (this.avatarBytes.length > 0)) this.avatar = ImageUtils.getScaledRoundedIcon(this.avatarBytes, AVATAR_ICON_WIDTH, AVATAR_ICON_HEIGHT); return this.avatar; }
private static boolean rotateImage( String imageFile, String outputFile, int quality, Bitmap.CompressFormat compressFormat) { int degree = ImageUtils.getExifOrientation(imageFile); if (degree != 0) { Log.i(TAG, "rotate image from:" + degree); Bitmap origin = BitmapFactory.decodeFile(imageFile); Bitmap rotate = ImageUtils.rotateImage(degree, origin); if (rotate != null) { ImageUtils.saveBitmap(rotate, outputFile, compressFormat, quality); rotate.recycle(); origin.recycle(); return true; } else { Log.i(TAG, "rotate image failed:" + imageFile); Log.i(TAG, "use origin image"); } origin.recycle(); } return false; }
/** * Gets the avatar of a specific <tt>MetaContact</tt> in the form of an <tt>ImageIcon</tt> value. * * @param isSelected indicates if the contact is selected * @param width the desired icon width * @param height the desired icon height * @return an <tt>ImageIcon</tt> which represents the avatar of the specified <tt>MetaContact</tt> */ public ImageIcon getAvatar(boolean isSelected, int width, int height) { byte[] avatarBytes = metaContact.getAvatar(true); // If there's no avatar we have nothing more to do here. if ((avatarBytes == null) || (avatarBytes.length <= 0)) { if (!subscribed) { return ImageUtils.getScaledRoundedIcon( ImageLoader.getImage(ImageLoader.UNAUTHORIZED_CONTACT_PHOTO), width, height); } return null; } // If the cell is selected we return a zoomed version of the avatar // image. if (isSelected) return ImageUtils.getScaledRoundedIcon(avatarBytes, width, height); // In any other case try to get the avatar from the cache. Object[] avatarCache = (Object[]) metaContact.getData(AVATAR_DATA_KEY); ImageIcon avatar = null; if ((avatarCache != null) && (avatarCache[0] == avatarBytes)) avatar = (ImageIcon) avatarCache[1]; // If the avatar isn't available or it's not up-to-date, create it. if (avatar == null) { avatar = ImageUtils.getScaledRoundedIcon(avatarBytes, width, height); } // Cache the avatar in case it has changed. if (avatarCache == null) { if (avatar != null) metaContact.setData(AVATAR_DATA_KEY, new Object[] {avatarBytes, avatar}); } else { avatarCache[0] = avatarBytes; avatarCache[1] = avatar; } return avatar; }
private static BufferedImage rotate(BufferedImage inImg, double angle) { BufferedImage outImg = ImageUtils.deepCopy(inImg); Graphics2D gr = (Graphics2D) outImg.getGraphics(); // rotate in center gr.rotate(angle, inImg.getWidth() / 2, inImg.getWidth() / 2); gr.drawImage(inImg, 0, 0, inImg.getWidth(), inImg.getWidth(), null); gr.dispose(); return outImg; }
/** * Create thumbnail for the image. * * @param image to scale. * @return the thumbnail image. */ private static BufferedImage createThumbnail(BufferedImage image) { int width = image.getWidth(); int height = image.getHeight(); // Image smaller than the thumbnail size if (width < THUMB_WIDTH && height < THUMB_HEIGHT) return image; Image i; if (width > height) i = image.getScaledInstance(THUMB_WIDTH, -1, Image.SCALE_SMOOTH); else i = image.getScaledInstance(-1, THUMB_HEIGHT, Image.SCALE_SMOOTH); return ImageUtils.getBufferedImage(i); }
/** * Establishes a call. * * @param isVideo indicates if a video call should be established. * @param isDesktopSharing indicates if a desktopSharing should be established. */ private void call(boolean isVideo, boolean isDesktopSharing) { ChatPanel chatPanel = chatContainer.getCurrentChat(); ChatSession chatSession = chatPanel.getChatSession(); Class<? extends OperationSet> opSetClass; if (isVideo) { if (isDesktopSharing) opSetClass = OperationSetDesktopSharingServer.class; else opSetClass = OperationSetVideoTelephony.class; } else opSetClass = OperationSetBasicTelephony.class; List<ChatTransport> telTransports = null; if (chatSession != null) telTransports = chatSession.getTransportsForOperationSet(opSetClass); List<ChatTransport> contactOpSetSupported; contactOpSetSupported = getOperationSetForCapabilities(telTransports, opSetClass); List<UIContactDetail> res = new ArrayList<UIContactDetail>(); for (ChatTransport ct : contactOpSetSupported) { HashMap<Class<? extends OperationSet>, ProtocolProviderService> m = new HashMap<Class<? extends OperationSet>, ProtocolProviderService>(); m.put(opSetClass, ct.getProtocolProvider()); UIContactDetailImpl d = new UIContactDetailImpl( ct.getName(), ct.getDisplayName(), null, null, null, m, null, ct.getName()); PresenceStatus status = ct.getStatus(); byte[] statusIconBytes = status.getStatusIcon(); if (statusIconBytes != null && statusIconBytes.length > 0) { d.setStatusIcon( new ImageIcon( ImageLoader.getIndexedProtocolImage( ImageUtils.getBytesInImage(statusIconBytes), ct.getProtocolProvider()))); } res.add(d); } Point location = new Point(callButton.getX(), callButton.getY() + callButton.getHeight()); SwingUtilities.convertPointToScreen(location, this); MetaContact metaContact = GuiActivator.getUIService().getChatContact(chatPanel); UIContactImpl uiContact = null; if (metaContact != null) uiContact = MetaContactListSource.getUIContact(metaContact); CallManager.call(res, uiContact, isVideo, isDesktopSharing, callButton, location); }
/** * 保存图片到指定的目录 * * @param bit * @param fileName 文件名 * @return */ public static String saveBitToSD(Bitmap bit, String fileName) { if (bit == null || bit.isRecycled()) return ""; File file = new File(Environment.getExternalStorageDirectory(), "/uniapp/photoCache"); File dirFile = new File(file.getAbsolutePath()); if (!dirFile.exists()) { dirFile.mkdirs(); } File pathFile = new File(dirFile, fileName); if (pathFile.exists()) { return pathFile.getAbsolutePath(); } else { ImageUtils.Bitmap2File(bit, pathFile.getAbsolutePath()); return pathFile.getAbsolutePath(); } }
@Test public void generateCaptcha() throws Exception { ImageUtils imageUtils = new ImageUtils(); imageUtils.setPath("captcha"); imageUtils.setBase("captcha"); imageUtils.setType("png"); imageUtils.setDefaultBackground(new Color(1f, 1f, 1f, 0f)); FileOutputStream os = new FileOutputStream("E:/test/sisda/captcha.png"); imageUtils.createCaptchaImage("Halo", os); os.close(); }
/** * Override paint method * * @see javax.swing.JComponent#paint(java.awt.Graphics) */ public void paint(Graphics inG) { super.paint(inG); if (_photo != null) { // read thumbnail in separate thread if (_thumbnail == null && !_loadingImage && !_loadFailed) { _loadingImage = true; new Thread(this).start(); } // if loading, display message if (_loadingImage) { inG.setColor(Color.BLACK); inG.drawString(LOADING_STRING, 10, 30); } else if (_thumbnail != null && !_loadFailed) { // Copy scaled, smoothed (and rotated) image into scaled int usableWidth = getParent().getWidth() - 10; int usableHeight = (_inPanel ? usableWidth : getHeight() - 10); Image scaled = ImageUtils.rotateImage( _thumbnail, usableWidth, usableHeight, _photo.getRotationDegrees()); int scaleWidth = scaled.getWidth(null); int scaleHeight = scaled.getHeight(null); // Draw scaled / rotated image to component int horizOffset = (getWidth() - scaleWidth) / 2; int vertOffset = (getHeight() - scaleHeight) / 2; inG.drawImage(scaled, horizOffset, vertOffset, scaleWidth, scaleHeight, null); // Special resize behaviour when locked inside details panel if (_inPanel && (getHeight() < getWidth() || getHeight() > usableWidth)) { Dimension newsize = new Dimension(usableWidth, usableWidth); setPreferredSize(newsize); setSize(newsize); invalidate(); // Schedule a relayout because the size has changed SwingUtilities.invokeLater( new Runnable() { public void run() { try { Thread.sleep(200); } catch (InterruptedException e) { } getParent().getParent().getParent().validate(); } }); } } } }
/** * Action performed on various action links(buttons). * * @param e the action. */ public void actionPerformed(ActionEvent e) { JButton src = (JButton) e.getSource(); if (src instanceof SIPCommButton) { // Load image int index = Integer.parseInt(src.getName()); BufferedImage image = AvatarStackManager.loadImage(index); // Set the new image setNewImage(image); } else if (src.getName().equals("chooseButton")) { // Open the image picker Image currentImage = this.avatarImage.getAvatar(); ImagePickerDialog dialog = new ImagePickerDialog(96, 96); byte[] bimage = dialog.showDialog(currentImage); if (bimage == null) return; // New image BufferedImage image = ImageUtils.getBufferedImage(new ImageIcon(bimage).getImage()); // Store image if (this.nextImageIndex == MAX_STORED_IMAGES) { // No more place to store images // Pop the first element (index 0) AvatarStackManager.popFirstImage(MAX_STORED_IMAGES); this.nextImageIndex = MAX_STORED_IMAGES - 1; } // Store the new image on hard drive AvatarStackManager.storeImage(image, this.nextImageIndex); // Inform protocols about the new image setNewImage(image); } else if (src.getName().equals("removeButton")) { // Removes the current photo. setNewImage(null); } else if (src.getName().equals("clearButton")) { clearRecentImages(); } setVisible(false); }
@Test public void generateText() throws IOException { ImageUtils imageUtils = new ImageUtils(); imageUtils.setPath("captcha"); imageUtils.setBase("captcha"); imageUtils.setType("png"); imageUtils.setDefaultBackground(new Color(1f, 1f, 1f, 0f)); FileOutputStream os = new FileOutputStream("E:/test/sisda/email.png"); imageUtils.createTextImage("*****@*****.**", os); os.close(); }
public static List<String> createThumbnails(MultipartFormData body, String folder) throws IOException, FileTooLargeException { // TODO Auto-generated method stub int index = -1; List<String> files = new ArrayList<>(); while (true) { FilePart picture = body.getFile("picture" + (index == -1 ? "" : index)); if (picture != null) { String fileName = picture.getFilename(); File file = picture.getFile(); System.out.println(file.length()); BufferedImage image = ImageIO.read(file); BufferedImage thumb = ImageUtils.resizeImage(image); Logger.error( "size: " + file.length() + " name: " + fileName + " " + fileName.lastIndexOf('.')); fileName = fileName.substring(0, fileName.lastIndexOf('.')); Logger.error( "size: " + file.length() + " name: " + fileName + " " + fileName.lastIndexOf('.')); int size = (int) (file.length() / 1024 / 1024); if (size > 1) { throw new FileTooLargeException(size + " " + 1); } File fileToSave = generateFileName(fileName, 0, folder); fileToSave.createNewFile(); ImageIO.write(thumb, "png", fileToSave); files.add(fileToSave.getPath().toString()); index++; } else break; } if (files.size() > 0) { return files; } return null; }
/** * Sets the icon for the given file. * * @param file the file to set an icon for * @return the byte array containing the thumbnail */ private byte[] getFileThumbnail(File file) { byte[] bytes = null; if (FileUtils.isImage(file.getName())) { try { ImageIcon image = new ImageIcon(file.toURI().toURL()); int width = image.getIconWidth(); int height = image.getIconHeight(); if (width > THUMBNAIL_WIDTH) width = THUMBNAIL_WIDTH; if (height > THUMBNAIL_HEIGHT) height = THUMBNAIL_HEIGHT; bytes = ImageUtils.getScaledInstanceInBytes(image.getImage(), width, height); } catch (MalformedURLException e) { if (logger.isDebugEnabled()) logger.debug("Could not locate image.", e); } } return bytes; }
/** * Request an image using the contents API if the source URI is a path to a file already in the * repository * * @param source * @return * @throws IOException */ private Drawable requestRepositoryImage(final String source) throws IOException { if (TextUtils.isEmpty(source)) return null; Uri uri = Uri.parse(source); if (!HOST_DEFAULT.equals(uri.getHost())) return null; List<String> segments = uri.getPathSegments(); if (segments.size() < 5) return null; String prefix = segments.get(2); // Two types of urls supported: // github.com/github/android/raw/master/app/res/drawable-xhdpi/app_icon.png // github.com/github/android/blob/master/app/res/drawable-xhdpi/app_icon.png?raw=true if (!("raw".equals(prefix) || ("blob".equals(prefix) && !TextUtils.isEmpty(uri.getQueryParameter("raw"))))) return null; String owner = segments.get(0); if (TextUtils.isEmpty(owner)) return null; String name = segments.get(1); if (TextUtils.isEmpty(name)) return null; String branch = segments.get(3); if (TextUtils.isEmpty(branch)) return null; StringBuilder path = new StringBuilder(segments.get(4)); for (int i = 5; i < segments.size(); i++) { String segment = segments.get(i); if (!TextUtils.isEmpty(segment)) path.append('/').append(segment); } if (TextUtils.isEmpty(path)) return null; List<RepositoryContents> contents = service.getContents(RepositoryId.create(owner, name), path.toString(), branch); if (contents != null && contents.size() == 1) { byte[] content = Base64.decode(contents.get(0).getContent(), DEFAULT); Bitmap bitmap = ImageUtils.getBitmap(content, width, MAX_VALUE); if (bitmap == null) return loading.getDrawable(source); BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; } else return null; }
public Drawable getDrawable(String source) { File output = null; try { output = File.createTempFile("image", ".jpg", dir); HttpRequest request = createRequest(source); if (!request.ok()) throw new IOException("Unexpected response code: " + request.code()); request.receive(output); Bitmap bitmap = ImageUtils.getBitmap(output, width, MAX_VALUE); if (bitmap == null) return loading.getDrawable(source); BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; } catch (IOException e) { return loading.getDrawable(source); } catch (HttpRequestException e) { return loading.getDrawable(source); } finally { if (output != null) output.delete(); } }