2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Quillで入力した画像をjsで取得する方法

Last updated at Posted at 2021-10-01

結論

以下のように取得したDELTA形式のデータをJSONとして扱い、画像データ部分を取得する。

概念コード.js
var quill = new Quill();
var contents = quill.getContents();//エディタに入力されている全内容の取得 DELTA形式

var img = new Image();
img.src = contents["ops"]["insert"]["image"] //DELTA形式はJSONと同様に扱えばいい

Quillって?

Ctrl+Vによる画像貼り付けにも対応したWYSIWIG テキストエディタ のインターフェースです。
簡単なhtml+jsで以下のようなテキストエディタUIをWEBページに埋め込むことができます。
image.png

例えば以下HTMLを作成し、ブラウザで開けます。簡単!!

入力データの取得とDELTA形式

入力データは getContents() によりデルタ形式で取得をします。

DELTA形式のデータは JSONの厳密なサブセット と記載があります
image.png

サンプルコード

submit ボタンを押すと、入力されている画像をページ上部に表示するサンプルページをつくりました。
image.png

quill.html
<html>
<header>
	<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
</header>
<body>
<div id="editor">
	<p>Hello Quill!</p>
	<div id="imageput"></div>
</div>
<form>
	<input type="button" onclick="click_action();" value="submit" />
</form>
<div id="edit"></div>
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<script>
  var quill = new Quill('#edit', {
    theme: 'snow'
  });

//=====================================================
//以下より拝借
//https://qiita.com/yasumodev/items/e1708f01ff87692185cd
// Base64形式の文字列 → <img>要素に変換
//   base64img: Base64形式の文字列
//   callback : 変換後のコールバック。引数は<img>要素
//=====================================================
function Base64ToImage(base64img, callback) {
    var img = new Image();
    img.onload = function() {
        callback(img);
    };
    img.src = base64img;
}

function click_action(){
	var content = quill.getContents();
	console.log(content);
	content["ops"].forEach((c) => {
		console.log(c);
		if('insert' in c){
			if(typeof(c["insert"]) === "string"){
			}
			else if('image' in c['insert']){
				console.log("GET IMAGE");
				Base64ToImage(c["insert"]["image"], function(img) {
				// <img>要素としてDOMに追加
				document.getElementById('imageput').appendChild(img);
				// <img>要素にすることで幅・高さがわかります
				var log = "w=" + img.width + " h=" + img.height;
				document.getElementById('log').value = log;
				});
			}
	}
	});
}
</script>
</body>



</html>

情報源

感謝!!

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?