• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala BufferedImage类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中java.awt.image.BufferedImage的典型用法代码示例。如果您正苦于以下问题:Scala BufferedImage类的具体用法?Scala BufferedImage怎么用?Scala BufferedImage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了BufferedImage类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: Bubble

//设置package包名称以及导入依赖的类
package com.alvinalexander.bubbles

import java.awt.Color
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.image.BufferedImage
import java.awt.GraphicsConfiguration
import java.awt.Transparency

case class Bubble (
    var x: Int, 
    var y: Int, 
    var lastX: Int, 
    var lastY: Int,
    circleDiameter: Int,
    fgColor: Color,
    bgColor: Color,
    char: Char
)
{
  
  private var image: BufferedImage = null
  
  def drawBubbleFast(g: Graphics, gc: GraphicsConfiguration) {
    val g2 = g.asInstanceOf[Graphics2D]
    if (image == null) {
      println("image was null")
      // build the image on the first call
      image = gc.createCompatibleImage(circleDiameter+1, circleDiameter+1, Transparency.BITMASK)
      val gImg = image.getGraphics.asInstanceOf[Graphics2D]
      renderBubble(gImg)
      gImg.dispose
    }
    g2.drawImage(image, x, y, null)
  }
  
  // given a Graphics object, render the bubble
  def renderBubble(g: Graphics) {
    val g2 = g.create.asInstanceOf[Graphics2D]
    // draw the circle
    g2.setColor(bgColor)
    g2.fillOval(0, 0, circleDiameter, circleDiameter)
    // draw the character
    g2.setFont(CIRCLE_FONT)
    g2.setColor(fgColor)
    g2.drawString(char.toString, CIRCLE_FONT_PADDING_X, CIRCLE_FONT_PADDING_Y)
    g2.dispose
  }
  
  
} 
开发者ID:arunhprasadbh,项目名称:AkkaKillTheCharactersGame,代码行数:52,代码来源:Bubble.scala


示例2: MNISTVisualizer

//设置package包名称以及导入依赖的类
package org.dl4scala.examples.feedforward.anomalydetection

import java.awt.{GridLayout, Image}
import java.awt.image.BufferedImage
import javax.swing.{ImageIcon, JFrame, JLabel, JPanel}

import org.nd4j.linalg.api.ndarray.INDArray

import scala.collection.mutable.ArrayBuffer


class MNISTVisualizer(imageScale: Double, digits: ArrayBuffer[INDArray], title: String, gridWidth: Int) {
  def this(imageScale: Double, digits: ArrayBuffer[INDArray], title: String) = {
    this(imageScale, digits, title, 5)
  }

  def visualize(): Unit = {
    val frame = new JFrame
    frame.setTitle(title)
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    val panel = new JPanel
    panel.setLayout(new GridLayout(0, gridWidth))
    val list = getComponents
    for (image <- list) {
      panel.add(image)
    }
    frame.add(panel)
    frame.setVisible(true)
    frame.pack()
  }

  def getComponents: ArrayBuffer[JLabel] = {
    val images = new ArrayBuffer[JLabel]()
    for (arr <- digits) {
      val bi = new BufferedImage(28, 28, BufferedImage.TYPE_BYTE_GRAY)
      for(i <- 0 until 784) {
        bi.getRaster.setSample(i % 28, i / 28, 0, (255 * arr.getDouble(i)).asInstanceOf[Int])
      }
      val orig = new ImageIcon(bi)
      val imageScaled = orig.getImage.getScaledInstance((imageScale * 28).asInstanceOf[Int],
        (imageScale * 28).asInstanceOf[Int], Image.SCALE_REPLICATE)
      val scaled = new ImageIcon(imageScaled)
      images.append(new JLabel(scaled))
    }
    images
  }
} 
开发者ID:endymecy,项目名称:dl4scala,代码行数:48,代码来源:MNISTVisualizer.scala


示例3: Barcodes

//设置package包名称以及导入依赖的类
package controllers

import play.api.mvc.{Action, Controller}

class Barcodes extends Controller {
  val ImageResolution = 144

  // png? ???? Action
  def barcode(ean: Long) = Action {
      import java.lang.IllegalArgumentException

      val MimeType = "image/png"
      try {
        val imageData = ean13BarCode(ean, MimeType)
        Ok(imageData).as(MimeType)
      }
      catch {
        case e: IllegalArgumentException =>
          BadRequest("Couldn't generate bar code. Error: " + e.getMessage)
      }
  }

  def ean13BarCode(ean: Long, mimeType: String): Array[Byte] = {
    import java.io.ByteArrayOutputStream
    import java.awt.image.BufferedImage
    import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider
    import org.krysalis.barcode4j.impl.upcean.EAN13Bean

    val output: ByteArrayOutputStream = new ByteArrayOutputStream
    val canvas: BitmapCanvasProvider = new BitmapCanvasProvider(
      output, mimeType, ImageResolution, BufferedImage.TYPE_BYTE_BINARY, false, 0)

    val barcode = new EAN13Bean()
    barcode.generateBarcode(canvas, String valueOf ean)
    canvas.finish

    output.toByteArray
  }
} 
开发者ID:makeajourney,项目名称:play-products-example,代码行数:40,代码来源:Barcodes.scala


示例4: OpenCVOps

//设置package包名称以及导入依赖的类
package com.dataoptimo.imgprocessing
import org.opencv.core.Mat
import javax.imageio.ImageIO
import java.io.ByteArrayInputStream
import java.awt.image.DataBufferByte
import org.opencv.core.CvType
import org.opencv.core.Core
import org.opencv.features2d.FeatureDetector
import org.opencv.core.MatOfKeyPoint
import org.opencv.features2d.Features2d
import org.opencv.highgui.Highgui
import java.awt.image.BufferedImage
import java.io.File



object OpenCVOps {
  
  System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  
  def imageToMat(byteArray: Array[Byte]): MatSer ={
      val bufferedImage = ImageIO.read(new ByteArrayInputStream(byteArray))
      val mat = new Mat(bufferedImage.getHeight(), bufferedImage.getWidth(), CvType.CV_8UC3);
      val data = bufferedImage.getRaster().getDataBuffer.asInstanceOf[DataBufferByte].getData();
      mat.put(0, 0, data);
      new MatSer(mat);
  }
  
  def matToImage(mat: Mat,file: String): Boolean ={
    
      val imageType = BufferedImage.TYPE_3BYTE_BGR;
      val image = new BufferedImage(mat.cols(),mat.rows(), imageType);
      val x = image.getRaster.getDataBuffer.asInstanceOf[DataBufferByte].getData
      mat.get(0,0,x)
      val fileName = new File("file")
      ImageIO.write(image, "jpg", fileName)
    
  }
  
  def detectFeatures(mat: Mat)
  {
    val featureDetector = FeatureDetector.create(FeatureDetector.SIFT)
    val matKeyPoint = new MatOfKeyPoint()
    featureDetector.detect(mat,matKeyPoint)
    println(mat.get(0, 0))
    println(matKeyPoint.toList())
    //writeToImage(mat,matKeyPoint)
    
  }
  
  def writeToImage(mat: Mat, matKeyPoint: MatOfKeyPoint){
    val outImage = new Mat()
    Features2d.drawKeypoints(mat, matKeyPoint, outImage)
    Highgui.imwrite("myfile.jpg",outImage)
    
  }
  
} 
开发者ID:mfawadalam,项目名称:imgprocessing,代码行数:59,代码来源:OpenCVOps.scala


示例5: Barcodes

//设置package包名称以及导入依赖的类
package controllers

import play.api.mvc.{Action, Controller}

class Barcodes extends Controller{
	val ImageResolution = 144

	def barcode(ean: Long) = Action{
		import java.lang.IllegalArgumentException

		val MimeType = "image/png"
		try{
			val imageData = ean13BarCode(ean, MimeType)
			Ok(imageData).as(MimeType)
		}catch{
			case e:IllegalArgumentException =>
			BadRequest("Couldn't generate bar code. Error: " + e.getMessage)
		}
	}

	def ean13BarCode(ean:Long, mimeType: String) : Array[Byte] = {
		import java.io.ByteArrayOutputStream
		import java.awt.image.BufferedImage
		import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider
		import org.krysalis.barcode4j.impl.upcean.EAN13Bean

		val output: ByteArrayOutputStream = new ByteArrayOutputStream
		val canvas: BitmapCanvasProvider = 
			new BitmapCanvasProvider(output, mimeType, ImageResolution,
				BufferedImage.TYPE_BYTE_BINARY, false, 0)

		val barcode = new EAN13Bean()
		barcode.generateBarcode(canvas, String valueOf ean)
		canvas.finish

		output.toByteArray
	}
} 
开发者ID:WackStr,项目名称:PlayProducts,代码行数:39,代码来源:Barcodes.scala


示例6: BrainfuckToKappaLang

//设置package包名称以及导入依赖的类
package com.lthummus.kappalang

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

import com.lthummus.kappalang.translator.EmoteTranslator._


object BrainfuckToKappaLang extends App {

  val bfCode = scala.io.Source.fromFile(args(0)).getLines.mkString
  val widthTokens = args(1).toInt
  val heightTokens = args(2).toInt

  val dir = args(3)
  val out = args(4)

  val SymbolMap = Map(
    '-' -> ImageIO.read(new File(dir + "BibleThump.png")),
    ']' -> ImageIO.read(new File(dir + "twitchraid.png")),
    '.' -> ImageIO.read(new File(dir + "KAPOW.png")),
    '[' -> ImageIO.read(new File(dir + "riPepperonis.png")),
    ',' -> ImageIO.read(new File(dir + "NotLikeThis.png")),
    '+' -> ImageIO.read(new File(dir + "Kappa.png")),
    '<' -> ImageIO.read(new File(dir + "RitzMitz.png")),
    '>' -> ImageIO.read(new File(dir + "FrankerZ.png"))
  )

  val NopFile = ImageIO.read(new File(dir + "nop.png"))

  if (heightTokens * widthTokens != bfCode.length) {
    println("Can't build that with the given dimensions")
    println("Dimensions given: " + widthTokens + "x" + heightTokens)
    println("Code length: " + bfCode.length)
  }

  val tokenCords = for {
    y <- 0 until heightTokens
    x <- 0 until widthTokens
  } yield (x * TokenWidth, y * TokenHeight)

  val symbols = bfCode.map(SymbolMap.getOrElse(_, NopFile))

  val image = new BufferedImage(widthTokens * TokenWidth,
    heightTokens * TokenHeight,
    BufferedImage.TYPE_INT_RGB)

  val graphics = image.getGraphics


  for (x <- tokenCords zip symbols) {
    graphics.drawImage(x._2, x._1._1, x._1._2, null)
  }

  ImageIO.write(image, "png", new File(out))

} 
开发者ID:LtHummus,项目名称:KappaLang,代码行数:59,代码来源:BrainfuckToKappaLang.scala


示例7: Barcodes

//设置package包名称以及导入依赖的类
package controllers

import play.api.mvc.{Action, Controller}

class Barcodes extends Controller {
  val ImageResolution = 144

  def barcode(ean: Long) = Action {
    import java.lang.IllegalArgumentException
    val MimeType = "image/png"
    try {
      val imageData = ean13BarCode(ean, MimeType)
      Ok(imageData).as(MimeType)
    }
    catch {
      case e: IllegalArgumentException =>
        BadRequest("Couldn’t generate bar code. Error: " + e.getMessage)
    }
  }

  def ean13BarCode(ean: Long, mimeType: String): Array[Byte] = {
    import java.io.ByteArrayOutputStream
    import java.awt.image.BufferedImage
    import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider
    import org.krysalis.barcode4j.impl.upcean.EAN13Bean
    val output: ByteArrayOutputStream = new ByteArrayOutputStream
    val canvas: BitmapCanvasProvider =
      new BitmapCanvasProvider(output, mimeType, ImageResolution,
        BufferedImage.TYPE_BYTE_BINARY, false, 0)
    val barcode = new EAN13Bean()
    barcode.generateBarcode(canvas, String valueOf ean)
    canvas.finish
    output.toByteArray
  }
} 
开发者ID:augfool,项目名称:scala_play2_web,代码行数:36,代码来源:Barcodes.scala


示例8: log

//设置package包名称以及导入依赖的类
package de.sciss.imperfect

import java.awt.Color
import java.awt.image.BufferedImage
import java.text.SimpleDateFormat
import java.util.{Date, Locale}

import scala.annotation.elidable
import scala.annotation.elidable.CONFIG

package object hough {
  var showLog = true

  private[this] val logHeader = new SimpleDateFormat("[d MMM yyyy, HH:mm''ss.SSS] 'imperfect' - ", Locale.US)

  final val NominalWidth  = 1920
  final val NominalHeight = 1080
  final val VisibleWidth  = 3840
  final val VisibleHeight =  540
//  final val OffScreenImg  = new BufferedImage(VisibleWidth, VisibleHeight, BufferedImage.TYPE_BYTE_GRAY)
  final val OffScreenImg  = new BufferedImage(VisibleWidth, VisibleHeight, BufferedImage.TYPE_INT_ARGB)
  final val OffScreenG    = {
    val res = OffScreenImg.createGraphics()
    res.setColor(Color.black)
    res.fillRect(0, 0, VisibleWidth, VisibleHeight)
    res
  }

  @elidable(CONFIG) def log(what: => String): Unit =
    if (showLog) Console.out.println(s"${logHeader.format(new Date())}$what")

  def warn(s: String): Unit =
    Console.err.println(s"Warning: $s")
} 
开发者ID:Sciss,项目名称:ImperfectHough,代码行数:35,代码来源:package.scala


示例9: render

//设置package包名称以及导入依赖的类
package eu.kraml.render

import java.awt.Color
import java.awt.geom.Ellipse2D
import java.awt.image.BufferedImage

import eu.kraml.Main.EventMonitor
import eu.kraml.model.{Circle, HeatMap, PointStyle, Record}
import eu.kraml.render.heatmap._

private[render] trait RecordRenderer {
    def render(overlay: BufferedImage, coordinateConverter: CoordinateConverter, records: List[Record])
              (implicit progress: EventMonitor): Unit
}

private[render] class CircleRenderer(private val diameter: Int, private val color: Color) extends RecordRenderer {
    private val radius = diameter/2.0

    override def render(overlay: BufferedImage, coordinateConverter: CoordinateConverter, records: List[Record])
                       (implicit progress: EventMonitor): Unit = {

        val awtG = overlay.createGraphics()
        awtG.setColor(color)

        val process = progress.startProcess("rendering point")
        process.setMaxProgressValue(records.size)

        records.foreach( r => {
            val center = coordinateConverter.toCanvasCoords(r.coordinate)
            val shape = new Ellipse2D.Double(center.x-radius, center.y-radius, diameter, diameter)
            awtG.fill(shape)
            process << 1
        })

        awtG.dispose()
        process.indicateCompletion()
    }
}


private[render] object RecordRenderer {
    def getRenderer(style: PointStyle): RecordRenderer =
        style match {
            case Circle(d, c) => new CircleRenderer(d, c.toAWT)
            case HeatMap() => new TiledRenderer(DefaultStyle)
            case _ => throw new IllegalArgumentException(s"unknown point style $style")
        }
} 
开发者ID:jkraml,项目名称:gpsplot,代码行数:49,代码来源:RecordRenderer.scala


示例10: getImageType

//设置package包名称以及导入依赖的类
package org.aj.awslambda

import java.awt.image.BufferedImage
import java.io.IOException
import java.net.URLDecoder

import com.amazonaws.services.lambda.runtime.events.S3Event
import java.util.regex.Pattern

import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global


  private def getImageType(srcKey: String): Option[String] = {
    val matcher = Pattern.compile(".*\\.([^\\.]*)").matcher(srcKey)
    matcher.matches() match {
      case true => {
        //get source image type and validate
        val imageType = matcher.group(1)
        imageTypes.get(imageType) match {
          case Some(_) => Some(imageType)
          case _ => None
        }
      }
      case _ => None
    }
  }

  private def decodeS3Key(key: String): String = URLDecoder.decode(key.replace("+", " "), "utf-8")

  private def process(srcBucket: String, srcKey: String, imageType: String, dstBucket: String): Future[List[Url]] = {

    //get source image with it's sizes
    val sourceImage: (BufferedImage, Url) = getImage(srcBucket, srcKey)
    //re-size
    val original: Future[Url] = process(sourceImage._1, sourceImage._2, imageType, dstBucket, srcKey)
    val resized: List[Option[Future[Url]]] = sizes.map { size =>
      if (sourceImage._2.width != size) Some(process(sourceImage._1, size, imageType, dstBucket, srcKey))
      else None
    }
    //return
    Future.sequence(original :: resized.flatten)

  }

} 
开发者ID:ajmnsk,项目名称:awslambda-resize,代码行数:47,代码来源:ImageHandler.scala


示例11: MyTestSuite

//设置package包名称以及导入依赖的类
package scalaview

import org.scalatest._
import Utils._

class MyTestSuite extends FunSuite {

  test("1+2=3") {
    assert(1 + 2 === 3)
  }

  test("thin(1) a finite stream") {
    val s1 = (1 to 10).toStream
    val s2 = thinStream(s1, 1)
    assert(s2.toList === s1.toList)
  }

  test("thin(2) a finite stream") {
    val s1 = (1 to 10).toStream
    val s2 = thinStream(s1, 2)
    assert(s2.toList === List(2, 4, 6, 8, 10))
  }

  test("thin(3) a finite stream") {
    val s1 = (1 to 10).toStream
    val s2 = thinStream(s1, 3)
    assert(s2.toList === List(3, 6, 9))
  }

  test("thin an infinite stream") {
    val s1 = Stream.iterate(1L)(_ + 1)
    val s2 = Stream.iterate(10000L)(_ + 10000)
    val s3 = thinStream(s1, 10000)
    assert(s2.take(1000).toList === s3.take(1000).toList)
  }

  test("rescale an image") {
    import java.awt.image.BufferedImage
    val im1 = new BufferedImage(100, 200, BufferedImage.TYPE_BYTE_GRAY)
    val im2 = biResize(im1, 1000, 2000)
    assert(im2.getWidth === 1000)
    assert(im2.getHeight === 2000)
  }

}

 
开发者ID:darrenjw,项目名称:scala-view,代码行数:46,代码来源:utils-tests.scala


示例12: JavaFontConversion

//设置package包名称以及导入依赖的类
package org.nspl
import java.awt.{Font => JFont}

object JavaFontConversion {
  implicit def font2font(myFont: Font): JFont = myFont match {
    case Monospace => new JFont(JFont.MONOSPACED, JFont.PLAIN, Monospace.size)
    case NamedFont(name, size) => new JFont(name, JFont.PLAIN, size)
  }

}

object AwtGlyphMeasurer extends GlyphMeasurer[Font#F] {
  import JavaFontConversion._
  import java.awt.image.BufferedImage
  val bimage = new BufferedImage(50, 50, BufferedImage.TYPE_BYTE_BINARY)
  val g2d = bimage.createGraphics();
  val frc = g2d.getFontRenderContext
  val abc =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQRSTUVWXYZ0123456789%,./][()]"
  def advance(s: Char, f: Font#F): Double =
    font2font(f).getStringBounds(s.toString, frc).getWidth
  def lineMetrics(f: Font#F): LineMetrics = {
    val lm = font2font(f).getLineMetrics(abc, frc)
    LineMetrics(lm.getAscent, lm.getDescent, lm.getLeading)
  }
} 
开发者ID:pityka,项目名称:nspl,代码行数:27,代码来源:font.scala


示例13: IconService

//设置package包名称以及导入依赖的类
package ylabs.play.common.services

import java.awt.Color
import java.awt.image.{ WritableRaster, BufferedImage }

import scala.util.Random

class IconService {
  def createImageWithBackground(image: BufferedImage, palette: List[Color]): BufferedImage = {
    val index = new Random().nextInt(palette.length)
    val backColor = palette.slice(index, index + 1).head
    val raster = image.copyData(null)
    val copy = new BufferedImage(image.getColorModel, raster, image.isAlphaPremultiplied, null)
    for {
      i ? 0 until copy.getWidth
      j ? 0 until copy.getHeight
    } yield {
      new Color(copy.getRGB(i, j), true) match {
        case c if c.getAlpha == 0 ?
          copy.setRGB(i, j, backColor.getRGB)
        case _ ?
      }
    }
    copy
  }
} 
开发者ID:springnz,项目名称:play-app-base,代码行数:27,代码来源:IconService.scala


示例14: IconServiceTest

//设置package包名称以及导入依赖的类
package ylabs.play.common.services

import java.awt.Color
import java.awt.image.BufferedImage

import ylabs.play.common.test.{ MyPlaySpec, OneAppPerTestWithOverrides }

class IconServiceTest extends MyPlaySpec with OneAppPerTestWithOverrides {
  "test background" in {
    val height = 30
    val width = 30
    val image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
    for {
      i ? 0 until height
      j ? 0 until width
    } yield {
      val color = new Color(0, 0, 0, i % 2)
      image.setRGB(i, j, color.getRGB)
    }

    val service = new IconService
    val newImage = service.createImageWithBackground(image, List(Color.red, Color.blue, Color.green))

    for {
      i ? 0 until height
      j ? 0 until width
    } yield {
      val origColor = new Color(0, 0, 0, i % 2)
      image.getRGB(i, j) shouldBe origColor.getRGB

      if (i % 2 == 0) newImage.getRGB(i, j) should (equal(Color.red.getRGB) or equal(Color.blue.getRGB) or equal(Color.green.getRGB))
      else newImage.getRGB(i, j) shouldBe origColor.getRGB
    }

  }
} 
开发者ID:springnz,项目名称:play-app-base,代码行数:37,代码来源:IconServiceTest.scala


示例15: Barcodes

//设置package包名称以及导入依赖的类
package controllers

import play.api.mvc.{Action, Controller}


class Barcodes extends Controller {
  val ImageResolution = 144

  def barcode(ean: Long) = Action {
    import java.lang.IllegalArgumentException

    val MimeType = "image/png"
    try {
      val imageData = ean13BarCode(ean, MimeType)
      Ok(imageData).as(MimeType)
    }
    catch {
      case e: IllegalArgumentException =>
      BadRequest("Couldn’t generate bar code. Error: " + e.getMessage)
    }
  }


  def ean13BarCode(ean: Long, mimeType: String): Array[Byte] = {
    import java.io.ByteArrayOutputStream
    import java.awt.image.BufferedImage
    import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider
    import org.krysalis.barcode4j.impl.upcean.EAN13Bean

    val output: ByteArrayOutputStream = new ByteArrayOutputStream
    val canvas: BitmapCanvasProvider =
      new BitmapCanvasProvider(output, mimeType, ImageResolution,
      BufferedImage.TYPE_BYTE_BINARY, false, 0)

    val barcode = new EAN13Bean()
    barcode.generateBarcode(canvas, String valueOf ean)
    canvas.finish

    output.toByteArray
  }

} 
开发者ID:ema00,项目名称:Play-Framework-CRUD,代码行数:43,代码来源:Barcodes.scala


示例16: Util

//设置package包名称以及导入依赖的类
package org.sparksamples

import java.awt.image.BufferedImage


object Util {
  def loadImageFromFile(path: String): BufferedImage = {
    import javax.imageio.ImageIO
    import java.io.File
    ImageIO.read(new File(path))
  }

  def processImage(image: BufferedImage, width: Int, height: Int): BufferedImage = {
    val bwImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY)
    val g = bwImage.getGraphics()
    g.drawImage(image, 0, 0, width, height, null)
    g.dispose()
    bwImage
  }

  def getPixelsFromImage(image: BufferedImage): Array[Double] = {
    val width = image.getWidth
    val height = image.getHeight
    val pixels = Array.ofDim[Double](width * height)
    image.getData.getPixels(0, 0, width, height, pixels)
    // pixels.map(p => p / 255.0) 		// optionally scale to [0, 1] domain
  }

  def extractPixels(path: String, width: Int, height: Int): Array[Double] = {
    val raw = loadImageFromFile(path)
    val processed = processImage(raw, width, height)
    getPixelsFromImage(processed)
  }


} 
开发者ID:PacktPublishing,项目名称:Machine-Learning-with-Spark-Second-Edition,代码行数:37,代码来源:Util.scala


示例17: BarcodesController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject._

import play.api._
import play.api.mvc._


class BarcodesController @Inject() extends Controller {
  val ImageResolution = 144

  def ean13BarCode(ean: Long, mimeType: String): Array[Byte] = {
    import java.io.ByteArrayOutputStream
    import java.awt.image.BufferedImage
    import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider
    import org.krysalis.barcode4j.impl.upcean.EAN13Bean

    val output: ByteArrayOutputStream = new ByteArrayOutputStream
    val canvas: BitmapCanvasProvider = new BitmapCanvasProvider(output, mimeType, ImageResolution, BufferedImage.TYPE_BYTE_BINARY, false, 0)
    val barcode = new EAN13Bean()
    barcode.generateBarcode(canvas, String valueOf ean)
    canvas.finish
    output.toByteArray
  }

  def barcode(ean: Long) = Action {
    import java.lang.IllegalArgumentException

    val MimeType = "image/png"

    try {
      val imageData = ean13BarCode(ean, MimeType)
      Ok(imageData).as(MimeType)
    } catch {
      case e: IllegalArgumentException =>
        BadRequest("Couldn’t generate bar code. Error: " + e.getMessage)
    }
  }
} 
开发者ID:yomajkel,项目名称:scala_play_book,代码行数:40,代码来源:BarcodesController.scala


示例18: BarcodesController

//设置package包名称以及导入依赖的类
package controllers



import javax.inject.{Inject, Singleton}
import play.api.mvc.{Action, Controller}


@Singleton
class BarcodesController @Inject() extends Controller {
  val ImageResolution = 144

  def barcode(ean: Long) = Action {
    import java.lang.IllegalArgumentException

    val MimeType = "image/png"
    try{
      val imageData = ean13BarCode(ean, MimeType)
      Ok(imageData).as(MimeType)
    }catch {
      case e: IllegalArgumentException =>
        BadRequest("Couldn't generate bar code. Error: " + e.getMessage)
    }

  }

  def ean13BarCode(ean: Long, mimeType: String) : Array[Byte] = {
    import java.io.ByteArrayOutputStream
    import java.awt.image.BufferedImage
    import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider
    import org.krysalis.barcode4j.impl.upcean.EAN13Bean
    var output: ByteArrayOutputStream = new ByteArrayOutputStream
    var canvas: BitmapCanvasProvider =
      new BitmapCanvasProvider(output, mimeType, ImageResolution,
        BufferedImage.TYPE_BYTE_BINARY, false, 0)

    val barCode = new EAN13Bean()
    barCode.generateBarcode(canvas, String valueOf ean)
    canvas.finish
    output.toByteArray
  }
} 
开发者ID:lanheixingkong,项目名称:product-list,代码行数:43,代码来源:BarcodesController.scala


示例19: PdfComparator

//设置package包名称以及导入依赖的类
package compare.pdfs

import java.awt.image.BufferedImage

import better.files.{File => ScalaFile}
import java.io.File

import scala.util.{Failure, Success, Try}


object PdfComparator {
  def compare(pdf1: ScalaFile, pdf2: ScalaFile): Try[Boolean] = {
    compare(pdf1.toJava, pdf2.toJava)
  }

  def compare(file1: File, file2: File): Try[Boolean] = {
    val tryPdfs = Seq(Try(new Pdf(file1)), Try(new Pdf(file2)))

    tryPdfs.filter(_.isFailure) match {
      case Failure(e) :: _ =>
        tryPdfs.filter(_.isSuccess).foreach(_.get.close())
        Failure(e)
      case _ =>
        val pdfs: Seq[Pdf] = tryPdfs.map(_.get)
        val Seq(pdf1Images: Seq[BufferedImage], pdf2Images: Seq[BufferedImage]) = pdfs.map(_.toImage)
        tryPdfs.foreach(_.get.close())
        pdf1Images.size == pdf2Images.size match {
          case true =>
            val comparisons = pdf1Images zip pdf2Images map (images => isSameImage(images._1, images._2))
            Success(!comparisons.contains(false))
          case _ => Success(false)
        }
    }
  }

  private def isSameImage(imgA: BufferedImage, imgB: BufferedImage): Boolean = {
    if (imgA.getWidth() == imgB.getWidth() && imgA.getHeight() == imgB.getHeight()) {
      val width: Int = imgA.getWidth
      val height: Int = imgA.getHeight

      val differentPixels =
        for (
          x <- 0 until width;
          y <- 0 until height
          if imgA.getRGB(x, y) != imgB.getRGB(x, y)
        ) yield (x,y)

      differentPixels.isEmpty
    }
    else false
  }
} 
开发者ID:hughlunt,项目名称:compare-pdfs,代码行数:53,代码来源:PdfComparator.scala


示例20: Test

//设置package包名称以及导入依赖的类
import java.awt.Color
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO


object Test {
  def main(args: Array[String]) {
    val image=new BufferedImage(400,400,BufferedImage.TYPE_4BYTE_ABGR)
    val graphics=image.createGraphics()
    graphics.setColor(Color.red)
    graphics.drawArc(-50,-50,100,100,0,360)
    graphics.setColor(Color.blue)
    graphics.fillArc(-50,-50,100,100,0,360)
    ImageIO.write(image,"jpg",new File("/home/yuan/workspace/IdeaProjects/ParallelizeHeatmap/source/p.jpg"))
  }
} 
开发者ID:yuanzhaokang,项目名称:ParallelizeHeatmap,代码行数:18,代码来源:Test.scala



注:本文中的java.awt.image.BufferedImage类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala SparkEnv类代码示例发布时间:2022-05-23
下一篇:
Scala Experimental类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap