【脱初心者】Spring Bootキャンプ【ハンズオン】に参加してきました
【脱初心者】Spring Bootキャンプ【ハンズオン】に参加!
9. WebRTCで撮った写真を顔変換サービスに送信 — Spring Bootキャンプ ハンズオン資料 1.0.0-SNAPSHOT ドキュメントまでは、コピペで動作確認。
その後なんとかTwitter4jを使って、顔変換した画像をツィートすることができました、、、汗
- pom.xml
Twitter4jを追加
<dependency> <groupId>org.twitter4j</groupId> <artifactId>twitter4j-core</artifactId> <version>[4.0,)</version> </dependency>
- twitter4j.properties
Twitter Developersでログイン後、「Manage Your Apps」リンクをクリック
「Create New App」で作成するアプリ名など指定して以下の設定値を取得
debug=true oauth.consumerKey=XXXXX oauth.consumerSecret=XXXXXXXXXX oauth.accessToken=XXXXXXXXXX oauth.accessTokenSecret=XXXXXXXXXX http.useSSL=true
以下の実装を追加(Spring Bootが全然初心者で、実装方法がいけてないと思うのですが、、、)
- App.java
Appクラスに以下の実装を追加
Twitter twitter = TwitterFactory.getSingleton(); @Autowired TwitterAuth twitterAuth; @PostConstruct void init() throws TwitterException{ twitter.verifyCredentials(); }
App#convertFaceメソッドに、ツィートするメソッド「twitterAuth.tweet」を追加
@JmsListener(destination="faceConverter", concurrency="1-5") void convertFace(Message<byte[]> message)throws IOException{ log.info("received!{}", message); try (InputStream stream = new ByteArrayInputStream(message.getPayload())){ Mat source = Mat.createFrom(ImageIO.read(stream)); faceDetector.detectFaces(source, FaceTranslator::duker); // リサイズ double ratio = ((double) resizedWidth) / source.cols(); int height = (int) (ratio * source.rows()); Mat out = new Mat(height, resizedWidth, source.type()); resize(source, out, new Size(), ratio, ratio, INTER_LINEAR); BufferedImage image = source.getBufferedImage(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream();){ ImageIO.write(image, "png", baos); baos.flush(); simpMessagingTemplate.convertAndSend("/topic/faces", Base64.getEncoder().encodeToString(baos.toByteArray())); twitterAuth.tweet(twitter, baos.toByteArray()); // <--この1行を追加 } } }
- TwitterAuthクラスを追加
@Component class TwitterAuth { private AtomicInteger PathCount = new AtomicInteger(); static final Logger log = LoggerFactory.getLogger(TwitterAuth.class); public void tweet(Twitter twitter, byte[] bytes) throws IOException { int pathNo = PathCount.getAndIncrement(); final Path path = Paths.get("/Users", "tomo", "test" + pathNo + ".png"); Files.deleteIfExists(path); try (FileOutputStream out = new FileOutputStream(path.toFile(), false);) { out.write(bytes); Status status2 = twitter.updateStatus(new StatusUpdate("test!").media(path.toFile())); log.info("Twitter text:{}", status2.getText()); } catch (Exception ex) { log.error("error {} {}", ex.getMessage(), path.toFile()); } }
Twitter4jで画像を扱うのはTwitter4Jで画像をアップロードしてみる - Challenge Java EE !を参考にさせていただきました。
- 強制的にシャットダウンするメモ
curl -X POST localhost:8080/shutdown
当日は、とても楽しい時間を過ごせました。スタッフの方々に、感謝感謝です!!!
また講師である@makingさん、とても勉強になりました。いろいろありがとうございました!
次はDockerに挑戦したいです、、、汗